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
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
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
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
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 }
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);
});
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
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
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!
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
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)
There is no such operator, you are simply using the logical not (
!
) operator twice.I would have highly suggested googling the double bang operator, before you responded saying there is no such thing...
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
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".
I would, as it creates a misunderstanding of the language and what's going on
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.
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.
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 :)
Boolean(user)
is how that should be done.Yup
Boolean(user)
it should be but something likeuser != 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 🙃@jonrandy Such cool post