preface
There is no end to learning, so learn
This article is a collection of commonly used features from ES6 to ES11, including ES12, which is still in the planning process. It only lists the general usage, but it will be very large if you go into details. PS: To use the new feature, you need to use the latest version of Bable to escape
This article will be updated in the long run
New features
ES6 (2015).
1. Class
Class Man {constructor(constructor(constructor) {this. constructor = 'constructor '; } console() { console.log(this.name); } const man = new man (new man); man.console(); / / small house
2. Modular (ES Module)
Export const sub = (A, b) => A + b; // Use import {sub} from './A'; console.log(sub(1, 2)); / / 3
3. Arrow function
const func = (a, b) => a + b; func(1, 2); / / 3
4. Default value of function parameters
function foo(age = 25,){ // ... }
5. Template strings
Const name = 'NULL '; const str = `Your name is ${name}`;
6. Deconstruct assignments
let a = 1, b= 2;
[a, b] = [b, a]; // a 2 b 1
The extension operator
let a = [...'hello world']; // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
8. Object property shorthand
Const obj = {name};
9. Promise
Promise.resolve().then(() => { console.log(2); }); console.log(1); // First print 1, then print 2
10. Let and const
Let name = 'Xiao Hao'; const arr = [];
ES7 (2016).
1. Array.prototype.includes()
[1].includes(1); // true
2. Exponential operator
2 * * 10; / / 1024
ES8 (2017).
1. async/await
The ultimate solution for asynchrony
async getData(){ const res = await api.getTableData(); // await asynchronous task // do something}
2. Object.values()
Object.values({a: 1, b: 2, c: 3}); / / [1, 2, 3]
3. Object.entries()
Object.entries({a: 1, b: 2, c: 3}); // [["a", 1], ["b", 2], ["c", 3]]
4. String padding
// padStart
'hello'.padStart(10); // " hello"
// padEnd
'hello'.padEnd(10) "hello "
Allow commas at the end of function argument lists
6. Object.getOwnPropertyDescriptors()
Gets the descriptor for all of the properties of an object, or returns an empty object if there are no properties of an object.
7. SharedArrayBuffer object
The ShareDarrayBuffer object is used to represent a generic, fixed-length buffer of raw binary data.
/** ** @param {*} length The size of the array buffer created, in bytes. * @Returns {ShareDarrayBuffer} A new ShareDarrayBuffer object of specified size. Its contents are initialized to 0. */ new SharedArrayBuffer(10)
8. Atomics object
The Atomics object provides a set of static methods used to perform atomic operations on the ShareDarrayBuffer object.
ES9 (2018).
1. Asynchronous iteration
Await can be equal to for… The of loops are used together to run asynchronous operations in a serial fashion
async function process(array) { for await (let i of array) { // doSomething(i); }}
2. Promise.finally()
Promise.resolve().then().catch(e => e).finally();
3. The Rest/Spread properties
const values = [1, 2, 3, 5, 6]; console.log( Math.max(... values) ); / / 6
4. Regular expression named capture group
const reg = /(? <year>[0-9]{4})-(? <month>[0-9]{2})-(? <day>[0-9]{2})/; const match = reg.exec('2021-02-23');
5. Regular expression reverse assertions
(? = p) and (? <=p) p before (position), p behind (position) (? ! P) and (? <! P >) except p in front (position), except p behind (position)
(? <=w)
(? <! w)
6. Regular expression dotAll pattern
Regular expression midpoint. Matching any single character except carriage return, the flag s changes this behavior, allowing line terminators to appear
/hello.world/.test('hello\nworld'); // false
ES10 (2019).
1. Array. Flat () and Array flatMap ()
flat()
[1, 2, [3, 4]].flat(Infinity); // [1, 2, 3, 4]
flatMap()
[1, 2, 3, 4].flatMap(a => [a**2]); // [1, 4, 9, 16]
2. String. TrimStart () and String. TrimEnd ()
Removes white space characters at the beginning and end of a string
3. String.prototype.matchAll
MatchAll () returns an iterator for all matched matches
const raw_arr = 'test1 test2 test3'.matchAll((/t(e)(st(\d?) )/g)); const arr = [...raw_arr];
4. Symbol.prototype.description
Read-only property, back to the string of optional descriptions of the Symbol object.
Symbol('description').description; // 'description'
5. Object.fromEntries()
Returns an array of key-value pairs for the enumerable properties of the given object itself
// const Map = new Map([['foo', 'bar'], ['baz', 42]]); console.log(Object.fromEntries(map)); // { foo: "bar", baz: 42 }
6. Optional Catch
ES11 (2020).
1. Nullish Coalescing Operator(Null Value Handling)
The expression in?? Returns the right-hand side of the operator that evaluates to undefined or null.
let user = { u1: 0, u2: false, u3: null, u4: undefined u5: '', } let u2 = user.u2 ?? 'user 2' // false let u3 = user.u3?? 'user 3' // user 3 let u4 = user.u4?? 'user 4' // let u5 = user.u5?? 'User 5' // ''
2. Optional chaining
? . User detects uncertain intermediate nodes
let user = {}
let u1 = user.childer.name // TypeError: Cannot read property 'name' of undefined
let u1 = user.childer?.name // undefined
3. Promise.allSettled
Returns a Promise that is resolved after all given Promises have been resolved or rejected, with an array of objects, each representing the corresponding Promise result
const promise1 = Promise.resolve(3); const promise2 = 42; Const promise3 = new Promise((resolve, reject) => reject(' I am a Promise_1')); Const promise4 = new Promise((resolve, reject) => reject(' I am a promise2 ')); const promiseList = [promise1,promise2,promise3, promise4] Promise.allSettled(promiseList) .then(values=>{ console.log(values) });
4. import()
According to the need to import
5. New base data type Bigint
An integer of arbitrary precision
6. globalThis
- Browser: Window
- Worker: the self
- Node: a global
ES12 (2021).
1. replaceAll
Returns a new string, and all characters that match the rules are replaced
const str = 'hello world';
str.replaceAll('l', ''); // "heo word"
2. Promise.any
Promise.any() receives a Promise iterable object and returns the successful Promise whenever one of the Promises succeeds. If none of the promises in the iterable object succeeds (i.e. all promises have failed/refused), a failed promise is returned
Const promise1 = new Promise((resolve, reject) => reject(' Promise_1')); const promise1 = new Promise((resolve, reject) => reject(' Promise_1')); Const promise2 = new Promise((resolve, reject) => reject(' I am a promise2 ')); const promiseList = [promise1, promise2]; Promise.any(promiseList) .then(values=>{ console.log(values); }) .catch(e=>{ console.log(e); });
3. WeakRefs
Use the Class Class of WeakRefs to create a weak reference to the object (a weak reference to the object means that it does not prevent GC from recycling when the object should be collected by GC)
4. Logical operators and assignment expressions
Logical operators and assignment expression, new features combined with logical operators, &&, | |,??) And an assignment expression. JavaScript’s existing compound assignment operators are:
A | | = b / / equivalent to a = a | | (a = b) a && = b / / equivalent to a = a && (a = b) a?? = b // is equivalent to a = a?? (a = b)
5. Numeric separators
Numeric delimiters. You can create visual delimiters between numbers that are separated by _ underscores to make the numbers more readable
const money = 1_000_000_000; // Equivalent to const money = 1000000000; 1 _000_000_000 = = = 1000000000; // true
Reference:
ES6, ES7, ES8, ES9, ES10 new features at a glance
Introduction to new ES11 features
Get first taste of the new JavaScript ES12 features
My blog
END