Home >Web Front-end >JS Tutorial >New JavaScript Features Every Developer Should Know

New JavaScript Features Every Developer Should Know

Barbara Streisand
Barbara StreisandOriginal
2024-12-28 22:05:11354browse

New JavaScript Features Every Developer Should Know

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:

code const user = { profile: { name: "John" } };
console.log(user.profile?.name);  // John
console.log(user.profile?.age);   // undefined

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 userName = '';
let defaultName = 'Guest';

console.log(userName ?? defaultName);  // 'Guest' because userName is an empty string

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 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 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 largeNumber = BigInt(1234567890123456789012345678901234567890);
console.log(largeNumber);

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:

let message = 'Hello World, Welcome to the World!';
let updatedMessage = message.replaceAll('World', 'Universe');
console.log(updatedMessage);  // Hello Universe, Welcome to the Universe!

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:

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

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:

code const user = { profile: { name: "John" } };
console.log(user.profile?.name);  // John
console.log(user.profile?.age);   // undefined

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:

let userName = '';
let defaultName = 'Guest';

console.log(userName ?? defaultName);  // 'Guest' because userName is an empty string

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

The above is the detailed content of New JavaScript Features Every Developer Should Know. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn