DEV Community

Subham Behera
Subham Behera

Posted on

Uncovering Hidden Gems in JavaScript

JavaScript is one of the most versatile and widely used programming languages in the world. It powers everything from simple websites to complex web applications. While many developers are familiar with its core features, JavaScript also has a plethora of lesser-known, yet incredibly useful, features that can make your code more efficient, elegant, and fun to write. In this blog post, we will explore some of these hidden gems that can take your JavaScript skills to the next level.

1. The ?? Nullish Coalescing Operator

The nullish coalescing operator (??) is a relatively new addition to JavaScript, introduced in ECMAScript 2020. It provides a way to handle null or undefined values without falling back on other falsy values like 0 or an empty string.

Example:

const name = null;
const defaultName = "Guest";

console.log(name ?? defaultName); // Output: Guest
Enter fullscreen mode Exit fullscreen mode

Use Case:

This operator is particularly useful when you want to assign default values to variables that may be null or undefined, but you don't want to override other falsy values.

2. The ?. Optional Chaining Operator

Optional chaining (?.) allows you to safely access deeply nested properties of an object without having to check each reference manually.

Example:

const user = {
  profile: {
    address: {
      city: "New York"
    }
  }
};

console.log(user.profile?.address?.city); // Output: New York
console.log(user.profile?.contact?.email); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

Use Case:

Optional chaining can save you from writing lengthy and error-prone conditional checks when accessing nested properties.

3. The !! Double Bang Operator

The double bang operator (!!) is a quick way to convert a value to its boolean equivalent.

Example:

const isAuthenticated = !!user; // Converts the truthiness of user to a boolean value
console.log(isAuthenticated); // Output: true or false
Enter fullscreen mode Exit fullscreen mode

Use Case:

This operator is handy for ensuring that a value is explicitly converted to true or false in a concise manner.

4. The ?.[] Optional Chaining with Dynamic Keys

Optional chaining also works with dynamic keys, which can be extremely useful when dealing with objects with dynamic property names.

Example:

const user = {
  settings: {
    theme: "dark"
  }
};

const key = "theme";
console.log(user.settings?.[key]); // Output: dark
console.log(user.settings?.[key]?.background); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

Use Case:

This feature is useful when accessing properties with dynamic keys, ensuring you avoid runtime errors.

5. The Object.fromEntries() Method

The Object.fromEntries() method transforms a list of key-value pairs into an object, which is the inverse operation of Object.entries().

Example:

const entries = [
  ['name', 'Alice'],
  ['age', 25]
];

const obj = Object.fromEntries(entries);
console.log(obj); // Output: { name: 'Alice', age: 25 }
Enter fullscreen mode Exit fullscreen mode

Use Case:

This method is great for converting data structures like maps or arrays of pairs into objects.

6. The import() Function for Dynamic Imports

The import() function allows you to dynamically load modules, which can be useful for code splitting and lazy loading in modern JavaScript applications.

Example:

import('./module.js')
  .then(module => {
    module.doSomething();
  })
  .catch(err => {
    console.error('Error loading module:', err);
  });
Enter fullscreen mode Exit fullscreen mode

Use Case:

Dynamic imports are perfect for improving performance by loading code only when it's needed.

7. The Proxy Object for Meta-Programming

The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.

Example:

const target = {
  message: "Hello, world!"
};

const handler = {
  get: (obj, prop) => {
    return prop in obj ? obj[prop] : "Property does not exist";
  }
};

const proxy = new Proxy(target, handler);
console.log(proxy.message); // Output: Hello, world!
console.log(proxy.nonExistentProperty); // Output: Property does not exist
Enter fullscreen mode Exit fullscreen mode

Use Case:

Proxies are powerful for adding custom behavior to objects, such as validation, logging, or modifying property access.

8. The Reflect API

The Reflect API provides methods for interceptable JavaScript operations. It's used in conjunction with Proxy to perform default operations.

Example:

const target = {
  message: "Hello, world!"
};

const handler = {
  set: (obj, prop, value) => {
    if (prop === "message" && typeof value !== "string") {
      throw new TypeError("Message must be a string");
    }
    return Reflect.set(obj, prop, value);
  }
};

const proxy = new Proxy(target, handler);
proxy.message = "Hi!"; // Works
proxy.message = 42;    // Throws TypeError: Message must be a string
Enter fullscreen mode Exit fullscreen mode

Use Case:

The Reflect API is useful for default operations in proxy traps, making your code more readable and less error-prone.

9. Tagged Template Literals

Tagged template literals allow you to parse template literals with a function. This can be useful for creating custom string processing functions.

Example:

function highlight(strings, ...values) {
  return strings.reduce((result, string, i) => {
    return `${result}${string}<span class="highlight">${values[i] || ''}</span>`;
  }, '');
}

const name = "JavaScript";
const sentence = highlight`Learning ${name} is fun!`;
console.log(sentence); // Output: Learning <span class="highlight">JavaScript</span> is fun!
Enter fullscreen mode Exit fullscreen mode

Use Case:

Tagged template literals are great for creating custom string formatting and processing functions.

10. The Intl Object for Internationalization

The Intl object provides language-sensitive string comparison, number formatting, and date and time formatting.

Example:

const date = new Date(Date.UTC(2020, 11, 20, 3, 0, 0));
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

console.log(new Intl.DateTimeFormat('en-US', options).format(date)); // Output: Sunday, December 20, 2020
console.log(new Intl.DateTimeFormat('de-DE', options).format(date)); // Output: Sonntag, 20. Dezember 2020
Enter fullscreen mode Exit fullscreen mode

Use Case:

The Intl object is invaluable for applications that need to support multiple languages and locales, providing consistent and accurate formatting.

Conclusion

JavaScript is full of hidden features that can make your code more powerful, efficient, and elegant. From the nullish coalescing and optional chaining operators to dynamic imports and the Intl object, these lesser-known features offer a treasure trove of functionality for developers. By incorporating these gems into your coding toolkit, you can write more expressive, maintainable, and efficient JavaScript.

Have you discovered any other hidden features in JavaScript that you find particularly useful? Share your thoughts in the comments below!

Top comments (11)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

The !! Double Bang Operator

There is no such operator, you are simply using the logical not (!) operator twice.

Collapse
 
wintersboy profile image
Adam Winters

I would have highly suggested googling the double bang operator, before you responded saying there is no such thing...

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Could you point out to me where in the list of unary operators in the official language specification it appears?

tc39.es/ecma262/#sec-unary-operators

Thread Thread
 
wintersboy profile image
Adam Winters

Ahh okay I misread what you said, sorry. It's technically not its own operator, just a combination of 2 logical nots.

However, it is widely known as the double bang operator so I wouldn't go as far as saying "there's no such operator".

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

I would, as it creates a misunderstanding of the language and what's going on

Thread Thread
 
wintersboy profile image
Adam Winters

I mean, the += operator isn't in the list of unary operators, but it's still widely used and known as a JavaScript operator.

He also never stated that !! was a unary operator.

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

The += operator isn't in the list of unary operators because it isn't one. It is an assignment operator. Assignment operators take two operands.

The very fact that he talked about it as a single operator and shows it used in the a manner it is - implies that he thinks it is a unary operator.

Thread Thread
 
nibelune profile image
Benoît Schiex

While Jon is technically right... the double bang name is widely used to name the trick of using 2 single bang operators to convert a value to boolean.

Documentations are not law books. take a seat and have a beer :)

Thread Thread
 
chovy profile image
chovy

Boolean(user) is how that should be done.

Thread Thread
 
samuel-braun profile image
Samuel Braun • Edited

Yup Boolean(user) it should be but something like user != null would be even better. Don't try and be smart with funky syntax. You could also use ~~number to floor it (5.123 becomes 5), but jokes on you when you run into negative numbers and get an off by one error 🙃

Collapse
 
deepak_vishwakarma_b61261 profile image
Deepak Vishwakarma

@jonrandy Such cool post