Lädt...


🔧 12 New JavaScript Features Every Developer Should Know


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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

...

🔧 Essential ES6 JavaScript Features Every JavaScript Developer Should Know


📈 40.82 Punkte
🔧 Programmierung

🔧 12 New JavaScript Features Every Developer Should Know


📈 37.88 Punkte
🔧 Programmierung

🔧 Unwrapping JavaScript ES2024: Key Features Every Developer Should Know


📈 35.47 Punkte
🔧 Programmierung

🔧 JavaScript ES6 Features Every Developer Should Know


📈 35.47 Punkte
🔧 Programmierung

🔧 JavaScript ES6 Features Every Developer Should Know


📈 35.47 Punkte
🔧 Programmierung

🔧 10 JavaScript Debugging Techniques Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Top 10 JavaScript Fundamentals That Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 10 JavaScript Super Hacks Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Decoding the Weird Parts of JavaScript Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 JavaScript tricks 🤯 that every developer should know


📈 30.33 Punkte
🔧 Programmierung

🔧 Unveiling the Dark Sides of JavaScript: Common Pitfalls Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 🌟 5 JavaScript Tricks Every Developer Should Know!


📈 30.33 Punkte
🔧 Programmierung

🔧 🚀Mastering JavaScript: Top 10 Concepts Every Developer Should Know!


📈 30.33 Punkte
🔧 Programmierung

🔧 🚀 5 Javascript concepts every web developer should know! 👨‍💻


📈 30.33 Punkte
🔧 Programmierung

🔧 🚀Mastering JavaScript: Top 10 Concepts Every Developer Should Know!


📈 30.33 Punkte
🔧 Programmierung

🔧 Writing Clean and Efficient JavaScript: 10 Best Practices Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Top 10 JavaScript Array Functions Every Senior Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Writing Clean and Efficient JavaScript: 10 Best Practices Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Top 5 JavaScript Libraries and Frameworks Every Developer Should Know in 2024


📈 30.33 Punkte
🔧 Programmierung

🔧 JavaScript 2024: Emerging Trends Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Top 3 JavaScript Concepts Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 20 JavaScript Tips Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Top 3 JavaScript Concepts Every Developer Should Know 🚀


📈 30.33 Punkte
🔧 Programmierung

🔧 Essential JavaScript Array Methods Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Unveiling the Art of JavaScript Debugging: Techniques Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Top 3 JavaScript Tricks Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 10 Essential JavaScript Snippets Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Unraveling Macrotasks and Microtasks in JavaScript: What Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Top 30 JavaScript Tricks Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 10 JavaScript Sites Every Web Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Top 30 JavaScript Tricks Every Developer Should Know


📈 30.33 Punkte
🔧 Programmierung

🔧 Every JavaScript developer should know this keyword: "defer" attribute ✨


📈 30.33 Punkte
🔧 Programmierung

🔧 5 JavaScript Patterns Every Developer Should Know in 2024


📈 30.33 Punkte
🔧 Programmierung

🔧 7 Essential JavaScript Unit Testing Frameworks Every Developer Should Know ✅


📈 30.33 Punkte
🔧 Programmierung

matomo