JavaScript is always evolving, and with each new version, it introduces features that make our lives as developers a little easier. Some of these features are game-changers, improving how we write and manage our code. If you’re a daily coder, it’s important to stay updated with these new features. In this post, I’ll walk you through some of the latest JavaScript features that are super useful and should be in your toolkit.
1. Optional Chaining (?.)
One of the most useful features added in recent versions of JavaScript is optional chaining. This allows us to safely access deeply nested properties in objects without worrying about whether an intermediate property is null or undefined.
Example:
Imagine you have a user object that may or may not have a profile:
code const user = { profile: { name: "John" } };
console.log(user.profile?.name); // John
console.log(user.profile?.age); // undefined
Without optional chaining, you would have to manually check each property, which can make the code messy. This small operator helps us avoid those checks, making the code cleaner and easier to read.
2. Nullish Coalescing Operator (??)
The nullish coalescing operator (??) is another neat feature introduced to help handle null or undefined values without affecting other falsy values like 0 or false.
Example
let userName = '';
let defaultName = 'Guest';
console.log(userName ?? defaultName); // 'Guest' because userName is an empty string
Unlike the logical OR (||), which treats an empty string ("") or 0 as falsy values, ?? will only return the right-hand operand if the left is null or undefined.
3. Promise.allSettled()
If you’re working with promises in JavaScript, you’ve probably used Promise.all(). But did you know there's a more powerful version called Promise.allSettled()? This method waits for all promises to settle, regardless of whether they were fulfilled or rejected. It’s super handy when you need to know the result of all promises, even if some fail.
Example:
const p1 = Promise.resolve(3);
const p2 = Promise.reject('Error');
const p3 = Promise.resolve(5);
Promise.allSettled([p1, p2, p3])
.then(results => {
console.log(results);
});
Output:
[
{ status: "fulfilled", value: 3 },
{ status: "rejected", reason: "Error" },
{ status: "fulfilled", value: 5 }
]
This is a great way to handle multiple async operations when you don’t want one failure to break the entire process.
4. BigInt for Large Numbers
We’ve all faced that problem of exceeding the limits of JavaScript’s Number type. JavaScript numbers are limited to values between -(2^53 - 1) and (2^53 - 1). If you need to work with numbers larger than that, BigInt is your friend.
Example:
const largeNumber = BigInt(1234567890123456789012345678901234567890);
console.log(largeNumber);
This will give you the ability to work with arbitrarily large integers without worrying about precision errors.
5. String.prototype.replaceAll()
If you’ve ever tried to replace all occurrences of a substring in a string, you probably used a regular expression with the replace() method. With replaceAll(), it’s much simpler. This method replaces all occurrences of a substring, and you don’t have to worry about global regex flags.
Example:
let message = 'Hello World, Welcome to the World!';
let updatedMessage = message.replaceAll('World', 'Universe');
console.log(updatedMessage); // Hello Universe, Welcome to the Universe!
It’s simple, cleaner, and gets rid of the need for regular expressions.
6. Logical Assignment Operators (&&=, ||=, ??=)
These new operators provide a shortcut to combine logical operators with assignments. They’re a great way to write more concise code.
-
&&=
: Assigns the value only if the left-hand value is truthy. -
||=
: Assigns the value only if the left-hand value is falsy. -
??=
: Assigns the value only if the left-hand value is null or undefined.
Example:
let count = 0;
count ||= 10; // count is now 10, because it was falsy
console.log(count); // 10
let name = null;
name ??= 'Anonymous'; // name is now 'Anonymous'
console.log(name); // Anonymous
These shortcuts help you reduce the verbosity of your code.
7. Object.fromEntries()
If you’ve ever needed to convert a list of key-value pairs into an object, Object.fromEntries() makes it easy. It’s particularly useful when you’re working with Map objects or arrays of tuples.
Example:
const entries = [['name', 'Alice'], ['age', 25]];
const person = Object.fromEntries(entries);
console.log(person); // { name: 'Alice', age: 25 }
This method is a cleaner, more readable alternative to manually constructing objects.
8. Array.prototype.flatMap()
This method is a combination of map() followed by flat(). It allows you to both map and flatten the results in a single step, which can be very useful when working with arrays of arrays.
Example:
const numbers = [1, 2, 3, 4];
const result = numbers.flatMap(x => [x, x * 2]);
console.log(result); // [1, 2, 2, 4, 3, 6, 4, 8]
This is cleaner than performing a map() followed by flat() separately.
9. Array.prototype.at()
This new method makes it easy to access elements from the end of an array using negative indexes. It’s much more intuitive than manually calculating the index for the last item.
Example:
const arr = [10, 20, 30, 40, 50];
console.log(arr.at(2)); // 30
console.log(arr.at(-1)); // 50
console.log(arr.at(-2)); // 40
It simplifies working with the last items in an array.
10. Top-Level Await
In JavaScript, we’ve always had to use await inside an async function. But with top-level await, you can now use await directly at the top level of modules, making your asynchronous code more straightforward.
Example:
// In an ES Module (.mjs or type="module")
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
This makes working with async code much simpler in modern JavaScript.
11. Private Class Fields
If you’ve ever wanted to make variables private in JavaScript classes, private class fields are now possible. You can now define variables that are not accessible from outside the class, using the # symbol.
Example:
class Person {
#name;
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
const person = new Person('John');
console.log(person.getName()); // John
This makes it easier to hide internal class details.
12. Stable Sort (Array.prototype.sort())
Previously, JavaScript’s sort() method was not stable, meaning equal items might be shuffled in an unpredictable way. Now, JavaScript ensures that elements with the same value retain their original order in the array.
Example:
const arr = [{ age: 30 }, { age: 20 }, { age: 30 }];
arr.sort((a, b) => a.age - b.age);
console.log(arr); // [{ age: 20 }, { age: 30 }, { age: 30 }]
This ensures a more predictable and consistent sort of behaviour.
Conclusion
JavaScript continues to evolve, and these features bring both convenience and power to developers. Whether you’re working with asynchronous code, handling large numbers, or just cleaning up your object and array manipulations, these new features can help you write cleaner, more efficient code. If you haven’t already, start experimenting with them in your projects, and see how they can make your workflow smoother.
Happy coding! 🚀
Please follow me to get more valuable content
Top comments (2)
Nice summary. For the record, I am convinced we do not need
class syntax
in ECMAScript/JS.Using Class Free Object Oriented coding, you can keep things private just as good. For example (click 'Preview' at the bottom of the code to see results):
dev.to/hanzla-baig/winterland-a-be...