Member-only story
10 JavaScript Tricks You Don’t Know

As one of the most popular languages, JavaScript’s syntax is flexible and continuously absorbs new features each year. Even seasoned professionals occasionally come across some underestimated JavaScript features and tricks. This article will share these tricks for discussion and exploration.
1. Using flatMap
Although some JavaScript methods are barely known, they possess the potential to enhance coding efficiency by resolving unique challenges, such as flatMap()
.
The array method flatMap() is essentially a combination of map() and flat(). The difference is that flatMap can only flatten 1 level, while flat can specify the number of levels to flatten. FlatMap is slightly more efficient than calling these two methods separately.
Using flat + map:
const arr = [1, 2, [4, 5], 6, 7, [8]];
// Use map to operate on each element and use flat to flatten the result
const result = arr.map(element => Array.isArray(element) ? element : [element]).flat();
console.log(result); // output: [1, 2, 4, 5, 6, 7, 8]
Using flatMap:
const arr = [1, 2, [4, 5], 6, 7, [8]] ;
console.log(arr.flatMap((element) => element));
// output :[1, 2, 4, 5, 6, 7, 8]
Although flatMap is a method, it still generates an intermediate array (which refers to a temporary array created for garbage collection). FlatMap is highly suitable for use in scenarios requiring flexibility and readability.
2. Array Method Order
javascript has dozens of array methods that can be used in combination. They look something like this:
const numbers = [9, 3, 6, 4, 8, 1, 2, 5, 7];
// Sort only for odd numbers and raise them to the power of 3
numbers
.sort((a, b) => a - b)
.filter((n) => n % 2 !== 0)
.map((n) => n ** 3);
The above code looks good, but there is an issue — sorting is done for the array before filtering. If the filtering is done before the sorting, we can accomplish fewer tasks, thereby optimizing the code.
const numbers = [9, 3, 6, 4, 8, 1, 2, 5, 7];
numbers
.filter((n) => n % 2 !== 0)
.sort((a, b) => a - b)
.map((n) => n ** 3);