ECMAScript, the standard behind JavaScript, is constantly evolving. While most developers are familiar with popular features like arrow functions and template literals, there are some hidden gems that often go unnoticed. Here are five ECMAScript features you probably didn’t know existed** but can supercharge your code:
Object.fromEntries()
This method transforms a list of key-value pairs into an object. It’s the reverse of Object.entries() and is perfect for converting data structures like Maps into objects.
javascript
const entries = [['name', 'Alice'], ['age', 25]];
const obj = Object.fromEntries(entries);
console.log(obj); // { name: 'Alice', age: 25 }Array.prototype.flatMap()
flatMap() combines map() and flat() into a single method. It’s ideal for mapping over an array and flattening the result by one level.
javascript
const numbers = [1, 2, 3];
const result = numbers.flatMap(x => [x, x * 2]);
console.log(result); // [1, 2, 2, 4, 3, 6]String.prototype.trimStart() and trimEnd()
These methods remove whitespace from the beginning or end of a string, respectively. They’re more intuitive than using trim() for specific cases.
javascript
const text = " Hello World! ";
console.log(text.trimStart()); // "Hello World! "
console.log(text.trimEnd()); // " Hello World!" Promise.allSettled()
Unlike Promise.all(), which fails if any promise rejects, allSettled() waits for all promises to complete, regardless of their status. It’s great for handling multiple asynchronous operations.
javascript
const promises = [Promise.resolve(1), Promise.reject('Error')];
Promise.allSettled(promises).then(results => console.log(results));globalThis
globalThis provides a universal way to access the global object, whether you’re in a browser, Node.js, or another environment.
javascript
console.log(globalThis === window); // true in browsers
console.log(globalThis === global); // true in Node.jsThese lesser-known ECMAScript features can simplify your code and make it more efficient. Start experimenting with them today to unlock their full potential!