Search⌘ K

What's new in ES2019?

Discover the key enhancements introduced in ES2019 including array flattening methods, converting key-value pairs to objects, improved string trimming, optional catch binding, and function source code representation. Understand how these features help write cleaner and more efficient JavaScript code.

We’ll look at what’s included in the latest version of ECMAScript: ES2019 in this lesson.

 

Array.prototype.flat() / Array.prototype.flatMap()

Array.prototype.flat() will flatten the array recursively up to the depth that we specify. If no depth argument is specified, 1 is the default value. We can use Infinity to flatten all nested arrays.

Node.js
const letters = ['a', 'b', ['c', 'd', ['e', 'f']]];
// default depth of 1
console.log(letters.flat());
// ['a', 'b', 'c', 'd', ['e', 'f']]
// depth of 2
console.log(letters.flat(2));
// ['a', 'b', 'c', 'd', 'e', 'f']
// which is the same as executing flat with depth of 1 twice
console.log(letters.flat().flat());
// ['a', 'b', 'c', 'd', 'e', 'f']
// Flattens recursively until the array contains no nested arrays
console.log(letters.flat(Infinity));
// ['a', 'b', 'c', 'd', 'e', 'f']

Array.prototype.flatMap() is identical to the previous one with regards to the way it handles the depth argument, but instead of simply flattening an array, with flatMap() we can ...