What's new in Javascript?
Tuesday, May 21, 2019 - 3 min read
Some of the new features are still proposal, so if you are playing with the code Some of the new features are still proposal, so if you are playing with the code, try to use Google Chrome.
Private Fields
1class Counter {
2 #counter = 0;
3
4 get value() {
5 return this.#counter;
6 }
7
8 increment() {
9 this.#counter++;
10 }
11}
12
13const counter = new Counter();
14counter.value(); // Output: 0;
15counter.increment(); // Output: 0;
16counter.value(); // Output: 1;
From the Counter class, the #counter
value is private, f we try to access the #counter
, then syntax error will be shown.
Rest/Spread Properties
The rest operator ...
copies the remaining property keys that were not mentioned. Let's look at an example:
1const values = { a: 1, b: 2, c: 3, d: 4 };
2const { a, ...n } = values;
3console.log(a); // prints 1
4console.log(n); // prints {b: 2, c: 3, d: 4}
Asynchronous Iteration
Now we can use await
on our loops declarations.
1for await (const line of readLines(filePath)) {
2 console.log(line);
3}
Regular Expression
JavaScript regular expressions can return a match object — an array-like value containing matched strings.
For example, to parse a date in YYYY-MM-DD format:
1const reDate = /([0-9]{4})-([0-9]{2})-([0-9]{2})/,
2 match = reDate.exec('2019-05-21'),
3 year = match[1], // 2019
4 month = match[2], // 05
5 day = match[3]; // 21
Array Flat
1const numbers = [1, 2, [3, 4, [5, 6]]];
2// Considers default depth of 1
3numbers.flat();
4> [1, 2, 3, 4, [5, 6]]
5// With depth of 2
6numbers.flat(2);
7> [1, 2, 3, 4, 5, 6]
8// Executes two flat operations
9numbers.flat().flat();
10> [1, 2, 3, 4, 5, 6]
11// Flattens recursively until the array contains no nested arrays
12numbers.flat(Infinity)
13> [1, 2, 3, 4, 5, 6]
Array.flat
will convert nested array items to a flat list.
By default, it will convert 1 level deep.
You can use:
1const array = [1, [2, [3, 4, [5, 6]]]];
2array.flat(Infinity);
The output will be 1, 2, 3, 4, 5, 6 if we use Infinity it will recursively convert to a flat list.
Set
The Set object lets you store unique values of any type, whether primitive values or object references.
Set objects are collections of values. You can iterate through the elements of a set in insertion order.
A value in the Set may only occur once; it is unique in the Set's collection.
1const duplicates = [1, 2, 3, 4, 1, 3, 4, 5];
2const uniques = Array.from(new Set(duplicates));
3
4console.log(uniques); //[1, 2, 3, 4, 5]
5
6const mySet = new Set();
7
8mySet.add(1); // Set [ 1 ]
9mySet.add(5); // Set [ 1, 5 ]
10
11mySet.has(1); // true
12
13mySet.size; // 5
14
15mySet.delete(5); // removes 5 from the set
16mySet.has(5); // false, 5 has been removed