What are ES2019 - ES10 features?

1. Array.prototype.flat() and Array.prototype.flatMap()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

const arr = [1, [2, 3], [4, [5, 6]]];
console.log(arr.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(arr.flat(2)); // [1, 2, 3, 4, 5, 6]

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array.

const arr = [1, 2, 3, 4];
console.log(arr.flatMap(x => [x * 2])); // [2, 4, 6, 8]
console.log(arr.flatMap(x => [[x * 2]])); // [[2], [4], [6], [8]]

2. Object.fromEntries()

The Object.fromEntries() method transforms a list of key-value pairs (typically from an array of entries) into an object.

const entries = [['name', 'Alice'], ['age', 25]];
const obj = Object.fromEntries(entries);
console.log(obj); // { name: "Alice", age: 25 }

3. String.prototype.trimStart() and String.prototype.trimEnd()

These methods are more specific than the trim() method, which removes whitespace from both ends.

const str = '  Hello world!  ';
console.log(str.trimStart()); // 'Hello world! '

const str = ' Hello world! ';
console.log(str.trimEnd()); // ' Hello world!'

4. Optional Catch Binding

In ES10, the catch clause no longer requires an error variable to be explicitly declared. If you don't need the error object in a try...catch block, you can omit it.

try {
throw new Error("Oops!");
} catch {
console.log("Error caught, but we don't need the error object");
}

5. Function.prototype.toString() Improvements

In ES10, the toString() method of functions now returns the exact source code of the function, including comments and whitespace, providing more transparency for developers working with function representations.

6. Symbol.prototype.description

ES10 added a description property to the Symbol prototype, which returns the description of a symbol.

const symbol = Symbol('mySymbol');
console.log(symbol.description); // 'mySymbol'

7. Well-formed JSON.stringify()

ES10 improved JSON.stringify() to handle well-formed UTF-8 output when dealing with special characters, ensuring compatibility with a wider range of character sets.

8. Array.prototype.sort() Stability

In ES10, the Array.prototype.sort() method became stable, meaning that when two elements are considered equal, their order in the sorted array will be preserved.

9. Array.prototype.unshift() and Array.prototype.push() with length

The behavior of Array.prototype.unshift() and Array.prototype.push() methods was improved to return the new array length, as expected. The length property can now be updated accurately when these methods are used in certain edge cases.