Home > Web Front-end > JS Tutorial > body text

Modern JavaScript Features: What's New in ES3

WBOY
Release: 2024-09-03 15:13:39
Original
850 people have browsed it

Modern JavaScript Features: What’s New in ES3

JavaScript is constantly evolving, and each year brings a new set of features designed to make developers' lives easier. ES2023, the latest update, is packed with new tools that enhance how we write, read, and maintain code. Let’s dive into some of the standout features that you’ll want to start using in your projects.

1. Array findLast and findLastIndex

Have you ever needed to find an item in an array starting from the end? ES2023 introduces findLast and findLastIndex, which do just that.

  • findLast: This method finds the last element in an array that meets a specified condition.
  const numbers = [1, 2, 3, 4, 5];
  const lastEven = numbers.findLast(num => num % 2 === 0); // 4

  // Find last user who is 18 years old in large array
  const users = [/* array with 10000 users */]; 
  users.findLast(user => user.age === 18);
Copy after login
  • findLastIndex: This method returns the index of that last element.
  const lastEvenIndex = numbers.findLastIndex(num => num % 2 === 0); // 3
Copy after login

These methods are great for those situations where you need to reverse your search logic, making your code clearer and potentially more efficient.

2. Hashbangs (#!) in JavaScript Files

If you’re writing command-line tools in JavaScript, you’ll appreciate the new support for hashbangs. By adding a #! at the top of your file, you can specify the interpreter directly, making your script executable without needing an external command.

#!/usr/bin/env node

console.log("Hello, world!");
Copy after login

This is a small but handy feature, especially for those who build CLI tools in Node.js.

3. Symbols as WeakMap Keys

Previously, only objects could be used as keys in WeakMap, but ES2023 changes that by allowing symbols as well.

const wm = new WeakMap();
const sym = Symbol('key');
wm.set(sym, 'value');

console.log(wm.get(sym)); // 'value'

// Storing hidden game data that players can't easily access, such as secret unlock codes:
const secretCode = Symbol('vc-cheat-code');
const gameData = new WeakMap();
gameData.set(secretCode, 'PANZER-ASPIRINE-BIGBANG-PRECIOUSPROTECTION'); 
Copy after login

This enhancement makes WeakMap even more versatile, particularly when you need unique, collision-free keys that symbols provide.

4. Array Grouping by Method

Grouping array elements has become a lot easier with the new group method.

  • group: This method organizes your array into an object, with keys determined by a function you provide and values as arrays of elements that match each key.
  const animals = [
    { type: 'mammal', name: 'dog' },
    { type: 'bird', name: 'sparrow' },
    { type: 'mammal', name: 'cat' },
  ];

  const grouped = animals.group(({ type }) => type);
  console.log(grouped);
  // {
  //   mammal: [{ type: 'mammal', name: 'dog' }, { type: 'mammal', name: 'cat' }],
  //   bird: [{ type: 'bird', name: 'sparrow' }]
  // }
Copy after login

This feature is perfect for scenarios where you need to categorize data quickly and efficiently.

5. Array.prototype.toSorted and Array.prototype.toReversed()

Sorting arrays just got a lot cleaner with toSorted. Unlike sort, which alters the original array, toSorted returns a new sorted array and toReversed returns a new reversed array, leaving the original untouched.

const arr = [3, 1, 4, 1, 5];
const sortedArr = arr.toSorted();
console.log(sortedArr); // [1, 1, 3, 4, 5]
console.log(arr); // [3, 1, 4, 1, 5]

let data = [/* important data that shouldn't be modified */];
let reversedData = data.toReversed(); // Safely reverse
Copy after login

This method is a great fit for when you need to preserve the original array while working with a sorted version.

6. Array.prototype.with

The with method provides a simple way to create a new array by replacing an element at a specific index.

const numbers = [10, 20, 30, 40];
const newNumbers = numbers.with(2, 25); // [10, 20, 25, 40]
Copy after login

This method is perfect when you want to update an array immutably, making it easier to manage state in functional programming patterns.

7. Promise.withResolvers

Managing promises has never been easier, thanks to Promise.withResolvers. This new method lets you create a promise along with its resolve and reject functions in one go.

const { promise, resolve, reject } = Promise.withResolvers();

setTimeout(() => resolve("done"), 1000);

promise.then(console.log); // "done"
Copy after login

It’s a neat and concise way to handle asynchronous operations, especially when you need to control the promise’s outcome from outside its constructor.

Browser Support for ES2023

ES2023, the latest version of JavaScript, is pretty new since it was just finished in 2023. This means not all web browsers can use its new features yet, but they're starting to:

  • Firefox, Chrome and Edge do support some features Array.prototype.findLast() and Array.prototype.findLastIndex()
  • Safari doesn't support any of these features yet.
  • Node.js

    • Node.js version 19.0 and up can use:
      • Array.prototype.findLast()
      • Array.prototype.findLastIndex() It's expected to add more ES2023 features in future updates.

Transpilers:
To use the new ES2023 features now, developers can turn ES2023 code into an older version that more browsers understand, using tools called transpilers, like Babel. This way, you can start using the new stuff even if browsers aren't ready for it yet.

Right now, the support for ES2023 is still growing. Big browsers like Firefox and Chrome are beginning to include some of its features. For details on what's supported where, you can check out Can I Use. Using transpilers helps make these new features usable today, while we wait for browsers to catch up over the coming years.

Conclusion

ES2023 brings a range of new features that make JavaScript more powerful and easier to work with. From enhanced array methods to better promise handling, these updates are all about making your code cleaner and more efficient. As JavaScript continues to grow and evolve, staying up-to-date with these changes ensures you’re always getting the most out of the language.

References:

  1. TC39 Proposals
  2. Draft ECMA-262
  3. MDN

The above is the detailed content of Modern JavaScript Features: What's New in ES3. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!