JavaScript is full of powerful features, but usually developers tend to rely on a small, familiar subset of its capabilities. Key methods cover array & string operations, object hadling, DOM interaction, and asynchronous operations.
Beyond the popular methods like map, filter, and reduce, there are functions and APIs that can significantly simplify the code and improve performance. Let’s explore some underrated JavaScript functions and patterns that deserve more attention.
1) Object.fromEntries() method transforms a list of key-value pairs into an object. It’s the reverse of Object.entries() and is perfect for transforming objects. Example:
const entries = [['name', 'Alice'], ['age', 25]];
const obj = Object.fromEntries(entries);
console.log(obj);
// { name: 'Alice', age: 25 }
Filtering object properties:
const user = { name: 'Alice', age: 25, isUser: false };
const filtered = Object.fromEntries(
Object.entries(user).filter(([_, value]) => value !== false)
);
console.log(filtered);
// { name: 'Alice', age: 25 }
2) Array.prototype.flatMap() method maps and flattens an array in one step. It avoids chaining .map().flat() and improves readability. Example:
const data = [1, 2, 3];
const result = data.flatMap(x => [x, x * 2]);
console.log(result);
// [1, 2, 2, 4, 3, 6]
3) Array.prototype.at() method accesses elements using positive or negative indices and is cleaner than arr[arr.length - 1]. Example:
const arr = [10, 20, 30];
console.log(arr.at(-1));
// 30
4) Promise.allSettled() method waits for all promises to settle (either fulfilled or rejected) and prevents one failure from stopping everything. Example:
const promises = [
Promise.resolve(1),
Promise.reject('Error'),
Promise.resolve(3)
];
const results = await Promise.allSettled(promises);
5) String.prototype.matchAll() method returns all matches of a regex, including capture groups. It's more powerful than match() when working with regex. Example:
const text = "test1 test2";
const regex = /test(\d)/g;
const matches = [...text.matchAll(regex)];
6) Array.prototype.findLast() and findLastIndex() search arrays from the end and are cleaner than reversing arrays. Example:
const arr = [1, 2, 3, 4, 5];
const lastEven = arr.findLast(i => i % 2 === 0);
console.log(lastEven);
// 4
7) queueMicrotask() schedules a microtask to run after the current execution and is more predictable than setTimeout(fn, 0). Example:
console.log('Start');
queueMicrotask(() => {
console.log('Microtask');
});
console.log('End');
// Output:
// Start
// End
// Microtask
Incorporating these functions into the workflow can:
- Reduce boilerplate code
- Improve readability and performance
- Make your code more powerful
If you want to level up as a JavaScript developer, it’s worth occasionally exploring the “forgotten corners” of the language—you might find tools that change how you write code completely
Top comments (0)