- read

10 JavaScript Tricks I Bet You Didn’t Know

Xiuer Old 80

10 JavaScript Tricks I Bet You Didn’t Know

Xiuer Old
JavaScript in Plain English
11 min read2 days ago

--

As one of the most popular languages, JavaScript has flexible syntax and continues to absorb new features every year. Even a veteran who has been in the industry for many years will occasionally have some underrated JavaScript functions and techniques. This article will share these techniques and discuss them together explore.Don’t be too serious about the title, it’s just a writing technique! (Escape)

1. Use flatMap

Some JavaScript methods are little known, but their potential to solve unique challenges can enhance coding efficiency, such as flatMap()

The array method flatMap() is essentially a combination of map()and flat(). The difference is that flatMap can only flatten one level, flat can specify the number of levels to be flattened, and flatmap is slightly more efficient than calling these two methods separately.

Use flat + map

const arr = [1, 2, [4, 5], 6, 7, [8]];

// Use map to operate on each element and flatten the result using flat
const result = arr.map(element => Array.isArray(element) ? element : [element]).flat();
console.log(result); // output: [1, 2, 4, 5, 6, 7, 8]

Use 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 will also produce intermediate arrays (referring to the creation of temporary arrays that must be garbage collected) . flatMap is very suitable for use when flexibility and readability are required.

2. Order of array methods

JavaScript has dozens of array methods, which can be combined together in a similar form:

const numbers = [9, 3, 6, 4, 8, 1, 2, 5, 7];

// Sort only odd numbers and raise them to powers 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 a problem — the array is sorted first and then filtered. If we filter first and then sort , we can complete fewer tasks and optimize the code.

const numbers = [9, 3, 6, 4, 8, 1, 2, 5, 7];

numbers
.filter((n) => n % 2 !== 0)
.sort((a, b) => a…