Translated and polished by Wu Liu, author: Twan Mulder

In September 1995, Brendan Eich, a programmer at Netscape, developed a new scripting language in just 10 days.

Initially, the scripting language was named Mocha, but soon became LiveScript, and later JavaScript.

Since its invention, JavaScript has become one of the most used programming languages in the world.

Every year, ECMA releases a version of JavaScript with new features. In this article, I’ll cover the best and most useful features introduced over the past four years.

ES2018

Expansion operator

One of the most interesting features in ES2015 is the Spread Operator. The expansion operator makes copying and merging arrays easier. Instead of calling concat() or slice(), you can use… Operator:

const array1 = [10.20.30];
const array2 = [40.50];
// merge arrays array2 and array1
const merge = [...array1, ...array2];
console.log(merge);
// Output result: [10, 20, 30, 40, 50]
Copy the code

ES2018 introduces the same concept, but for objects:

const object = {
  a: 1.b: 2.c: 3
};
const{ a, ... x } = object;console.log(a)
console.log(x)
// Output result:
// a = 1
// x = { b: 2, c: 3 }
Copy the code

Also, the expansion operator can be used in other objects, such as:

const object1 = { a: 1.b: 2.c: 3 };
constobject2 = { ... object1,z: 26 };
console.log(object2)
// Output result:
// { a: 1, b: 2, c: 3, z: 26 }
Copy the code

Promise.prototype.finally()

Another exciting feature of ES2018 is the finally() method.

There are JavaScript libraries in the community that implement a similar approach, which can be useful in many scenarios.

Using the finally() method, you can execute a piece of code without worrying about what the state of the Promise is. Let’s look at a simple example:

fetch('file.json')
  .then(data= > data.json())
  .catch(error= > console.error(error))
  .finally(() = > console.log("finished"))
// Output result: "finished" (independent of the fetch result)
Copy the code

ES2019

flat()

The flat() method lets you easily flatten all the subarray elements of an array. For example, here is an example:

const arr = ['a'.'b'['c'.'d']].const flattened = arr.flat();
console.log(flattened);    
["a", "b", "c", "d"]
Copy the code

Obviously, until now you can only use reduce() or concat() to get the flattened array:

const arr = ['a'.'b'['c'.'d']].const flattened = [].concat.apply([], arr);
/ / or
// const flattened =  [].concat(...arr);
console.log(flattened);    
["a", "b", "c", "d"]
Copy the code

Object.fromEntries()

Converting data from one format to another is a common scenario when working with JavaScript. To make it easier to convert Object to Array, ES2017 introduced the object.entries () method. This method takes the object as an argument and returns the object’s own Enumerable string key and attribute Property as [key, value].

But what if we wanted to do the opposite and turn the list of key-value pairs into objects?

ES2019 introduces a new feature, the object.fromentries () method, which you can use to:

const myArray = [['one'.1], ['two'.2], ['three'.3]].const obj = Object.fromEntries(myArray);
console.log(obj);    
{one: 1, two: 2, three: 3}
Copy the code

ES2020

Optional chain operator

Optional Chaining operators will make your code more readable!

The optional chain operator allows you to access nested object properties each time without having to verify that the parent property exists.

Here’s an example to compare:

// The optional chain operator is not used
let userAdmin = undefined;
if (payload.access && payload.access.admin && payload.access.admin[0]) {
  userAdmin = payload.access.admin[0].user;
}
// Use the optional chain operator
constuserAdmin = payload.access? .admin? [0]? .user;Copy the code

As you can see, instead of declaring a variable with conditions to assign to it, we can declare const on a line without any conditions.

If no property on the object is found, undefined is returned. This is really useful!

Null-value merge operator

The Nullish Coalescing operator adds the ability to actually check Nullish, rather than whether it is false. So, I think you might ask what’s the difference between null and false?

In JavaScript, many values converted to Boolean types are false, such as empty strings, digits 0, undefined, null, flase, NaN, and so on.

Before null-value merge operators, many times you might want to check if a variable is null. It could be undefined, NULL, an empty string, or even a false.

So, in this case, you can use the null value merge operator? Easy to handle! And, I think this time, may have a homecoming say | | not have the same effect? Here, come by example we see the | | and?? Different places:

console.log(0 ?? true) / / 0
console.log(0 || true) // true
console.log(' ' ?? 'Hello World! ') / /"
console.log(' ' || 'Hello World! ') // 'Hello World! '
console.log(false ?? true) // false
console.log(false || true) // true
console.log(NaN ?? 5) // Nan
console.log(NaN || 5) / / 5
console.log(null ?? true) // true
console.log(null || true) // true
Copy the code

ES2021

String.prototye.replaceAll

String. The prototype. The replaceAll () method can be implemented using another String the goals of the value of the replacement String pattern part of all of the String.

In JavaScript, the.replace() method replaces only the first string in the target string that satisfies the pattern part:

let string = "Wow, he doesn't like Porsche? I guess he must be crazy!"
string.replace("he"."she")
"Wow, she doesn't like Porsche? I guess he must be crazy!"
Copy the code

If we want to replace all strings that meet the pattern part, the only way to do this is through global matching using regular expressions. While using regular expressions is not a bad approach, it is not the best from a performance standpoint.

With the.replaceAll() method, we can update all strings that match pattern at once without creating regular expressions:

let string = "Wow, he doesn't like Porsche? I guess he must be crazy!"
string.replaceAll("he"."she")
"Wow, she doesn't like Porsche? I guess she must be crazy!"
Copy the code

Number separator

For now, Numeric Separators is mostly a cosmetic change that has little impact on the performance of the actual code, but it may help avoid errors when you need to insert values into your code.

Numeric separators will speed up reading numbers, although this is a very small improvement. Even though the introduction of numeric separators is not a huge update, it will not change our program. However, there’s no denying that number separators are a great feature:

const MILLION = 1 _000_000;       / / 1000000
const BILLION = 1 _000_000_000;   / / 1000000000
Copy the code

And the cool thing about number separators is that they can be used after the decimal point! Now, let’s take a look at the corresponding use:

const BIGNUMBER = 1234 _5678_9_0;  / / 1234567890
const PI = 3.1415 _9265_3589;     / / 3.141592653589
Copy the code

Also note that ReferenceError and SyntaxError will be raised for integers and numbers beginning or ending with an underscore:

const BAD_PI = 3.14 _15_;// SyntaxError
const NO_MILLION = _1_000_000;    // ReferenceError
Copy the code

Thumb up 👍

If you get something from this post, please give me a “like”. This will be my motivation to keep sharing. Thank you

My name is Wu Liu. I like innovation and source Code manipulation, and I focus on source Code (Vue 3, Vite), front-end engineering, cross-end and other technology learning and sharing. Welcome to follow my wechat official account: Code Center.