Freshly baked, integrating the new features of es7-11 in recent years

Time:2021-7-27

The original intention of this article is as follows:

  1. The reason is to understand the support of browsers in different stages for some methods, so as to facilitate and quickly locate the compatibility problems under different browsers;
  2. At the same time, as a document reference, you can more clearly understand the new features of each stage;
  3. Help everyone get extra points in the interview. Being familiar with the updated details of each stage will always give the interviewer a good impression;

I would like to encourage you and give you a compliment if it is helpful. Thank you~~

New features of es11 (released in 2020)

Version 11 of ECMAScript language specification.

String.prototype.matchAll(regexp)

matchAllMethod returns an iterator containing the results of all matching regular expressions and the group capture group.

Input:regexpIs a regular expression object. If the parameter passed is not a regular expression object, it is implicitly usednew RegExp(obj)Convert it to aRegExp

Return: an iterator (not reusable, the result is exhausted, and the method needs to be called again to get a new iterator).

  • Basic use
const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";

//Return iterator
const iterator = str.matchAll(regexp);
const array = [...iterator];

console.log(array[0]);
// expected output: Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// expected output: Array ["test2", "e", "st2", "2"]
  • Console execution

Freshly baked, integrating the new features of es7-11 in recent years

  • matters needing attention:matchAllInput parameterregexpMust keep upgSearch by full text, otherwise it will be thrownTypeErrorabnormal

    • /i: ignore case
    • /g: find all matching characters that appear in the full text
    • /m: multiline lookup
    • /ig: full text lookup, ignoring case

Freshly baked, integrating the new features of es7-11 in recent years

  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Dynamic import

Standard usageimportThe imported module is static, which will make all imported modules compiled when loaded (unable to compile on demand and reduce the loading speed of the home page).

In some scenarios, you may want to import modules according to conditions or on demand. In this case, you can use dynamic import instead of static import. Here are the scenarios you may need to import dynamically:

  • Usage scenario

    • When the statically imported module obviously reduces the loading speed of the code, and the possibility of being used is very low, or it does not need to be used immediately.
    • When statically imported modules obviously occupy a lot of system memory and are very unlikely to be used.
    • When the imported module does not exist during loading, it needs to be obtained asynchronously
    • When importing the specifier of the module, it needs to be built dynamically( Static import (only static specifiers can be used)
    • When the imported module has side effects (the side effects mentioned here can be understood as the code that will run directly in the module), these side effects are required only when certain conditions are triggered( In principle, modules can’t have side effects, but in many cases, you can’t control the content of the modules you depend on)
  • General is used as asynchronous on-demand loading
function callback() {
  //Await is also supported
  import("moduleB")
    .then((module) => {
      // todo
    })
    .catch((err) => {
      // load error
    });
}
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

import.meta

import.metaIs an object that exposes metadata attributes of a specific context to a JavaScript module. It contains the information of the module, such as the URL of the module.

  • Basic use

    • adoptscriptReference label
    <script type="module"></script>;
    
    //Used in my-module.mjs
    console.log(import.meta); // { url: "file:///home/user/my-module.mjs" }
    • adoptimportquote
    // a.js
    import "b.js?param1=test";
    
    // b.js
    import.meta.url; // ...b.js?param1=test
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

export * as alias from namespace

Module redirection

  • Basic use
//If we want to export the default export of the specified import module in the current module (equivalent to creating a "redirect"):
// module "redirect-module.js"
export {default} from './other-module';
export * from './other-module';
export * as otherName from './other-module';
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Promise.allSettled(iterable)

Input parameter: an iteratable object in which each member isPromise

Return: one at all givenpromiseAll alreadyfulfilledorrejectedPosteriorpromiseWith an array of objects, each object represents the correspondingpromiseresult.

When you have multiple asynchronous tasks that do not depend on each other to complete successfully, or you always want to know each onepromiseThe result is usually used.

by comparison,Promise.all()More suitable for interdependence or in any one of themrejectEnd immediately when.

  • Basic use
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) =>
  setTimeout(reject, 100, "foo")
);
const promises = [promise1, promise2];

Promise.allSettled(promises).then((results) =>
  results.forEach((result) => console.log(result.status))
);

// Promise {<pending>}
// fulfilled
// rejected
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

BigInt

The latest ECMAScript standard defines 8 data types: 7 original types: Boolean, null, undefined, number, bigint, string and symbol; And object;

BigIntType is a basic numeric type in JavaScript, which can represent integers with any precision. With bigint, you can safely store and manipulate large integers, even exceeding the safe integer limit of numbers.

BigIntIs a built-in object that provides a way to represent greater than2^53 - 1Integer of. This was originally available in JavaScriptNumberRepresents the maximum number of.BigIntCan represent an integer of any size.

BigIntIs by appendingn Or call the constructor to create.

By using constantsNumber.MAX_SAFE_INTEGER(2 ^ 53 – 1), you can get the safest value that can be incremented by numbers. By introducing bigint, you can operate more thanNumber.MAX_SAFE_INTEGERNumber of.

YesBigIntUse operator +、`-、* and%`, just like numbers. Bigint is not strictly equal to a number, but it is loose.

  • Basic use
const x = 2n ** 53n;
// ↪ 9007199254740992n
const y = x + 1n;
// ↪ 9007199254740993n
const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
// ↪ 9007199254740991n
const maxPlusOne = previousMaxSafe + 1n;
// ↪ 9007199254740992n
const theFuture = previousMaxSafe + 2n;
// ↪ 9007199254740993n, this works now!
const multi = previousMaxSafe * 2n;
// ↪ 18014398509481982n
const subtr = multi – 10n;
// ↪ 18014398509481972n
const mod = multi % 10n;
// ↪ 2n
const bigN = 2n ** 54n;
// ↪ 18014398509481984n
bigN * -1n
// ↪ –18014398509481984n
  • In willBigIntConvert toBooleanWhen, it behaves like a number: if、`||、&&、Boolean and`!。
0n === 0;
// ↪ false
0n == 0;
// ↪ true
  • BigIntCannot operate interchangeably with numbers. Otherwise, it will be thrownTypeError
1 + 1n; // Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
  • When usedBigIntWhen, operations with decimals are rounded.
const expected = 4n / 2n;
// ↪ 2n
const rounded = 5n / 2n;
// ↪ 2n, not 2.5n
  • Number and bigint can be compared
1n == 1;
// ↪ true
1n === 1;
// ↪ false
1n < 2;
// ↪ true
2n > 1;
// ↪ true
2 > 2;
// ↪ false
2n > 2;
// ↪ false
2n >= 2;
// ↪ true

//The two can also be mixed together for comparison
const mixed = [4n, 6, -12n, 10, 4, 0, 0n];
// ↪  [4n, 6, -12n, 10, 4, 0, 0n]
mixed.sort();
// ↪ [-12n, 0, 0n, 10, 4n, 4, 6]

//Note that bigints wrapped by object are compared using object's comparison rules. Only the same object will be equal during comparison.
0n === Object(0n); // false
Object(0n) === Object(0n); // false
0n === 0n; // true
const o = Object(0n);
o === o; // true
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

globalThis

Global propertiesglobalThisInclude globalthisValue, similar to global object.

  • In different environments before

    • webMedium: YeswindowselfperhapsframesGet global object
    • Web WorkersChinese: onlyselfsure
    • Node.jsMedium: must be usedglobal
    • In loose mode, you canthisTo get the global object
    • In strict mode,thisWill returnundefined, you canfunction(){return this}
  • globalThisIt provides a standard way to obtain global information in different environmentsthisObject (global object itself)

    NowindowperhapsselfThese properties ensure that it can work properly in various environments with or without windows. So you can use it safelyglobalThis, don’t worry about its running environment. To make it easier to remember, you just need to remember that in the global scopethisnamelyglobalThis

  • HTML and windowproxy

    In many engines,globalThisIt is considered to be the reference of real global objects, but in the browser, due to the consideration of iframe and cross window security, it actually refers to the reference of real global objects (which can not be accessed directly)ProxyAgent. In common applications, the difference between proxy and object itself is rarely involved, but it also needs to be paid attention to.

  • Basic use
//There is no uniform way to get global objects before globalthis
var getGlobal = function () {
  if (typeof self !== "undefined") {
    return self;
  }
  if (typeof window !== "undefined") {
    return window;
  }
  if (typeof global !== "undefined") {
    return global;
  }
  throw new Error("unable to locate global object");
};

var globals = getGlobal();

if (typeof globals.setTimeout !== "function") {
  //There is no setTimeout method in this environment!
}

//With globalthis, just
if (typeof globalThis.setTimeout !== "function") {
  //There is no setTimeout method in this environment!
}
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Optional chaining (?.)

Optional chainOperator(?.)Allows you to read the value of an attribute deep in the chain of connected objects without explicitly verifying that each reference in the chain is valid.?.The function of the operator is similar to.Chain operator, the difference is that the reference is empty(nullperhapsundefined)Will not cause an error, and the return value of the expression isundefined

When used with a function call, returns if the given function does not existundefined

  • grammar
obj?. Prop // object properties
obj?.[ Expr] // object expression
arr?.[ Index] // array index
func?.( Args) // method call
  • Basic use
const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

//Nonexistent property
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

//Nonexistent function
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
  • Used in the past
//No
let nestedProp = obj.first && obj.first.second;

//Use
//By using The. Operator is replaced by the. Operator. Before JavaScript attempts to access obj.first.second,
//1. Implicitly check and confirm that obj.first is neither null nor undefined.
//2. If obj.first is null or undefined, the expression will be short circuited and the calculation will directly return undefined.
let nestedProp = obj.first?.second;

//Equivalent to
let temp = obj.first;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
  • And function call

Note: if there is an attribute name and it is not a function, use A typeerror exception (x.y is not a function) will still be generated

//When methods using an API may not be available
//When calling a function, if the called method does not exist, using an optional chain can make the expression automatically return undefined instead of throwing an exception.
let result = someInterface.customMethod?.();

//Old writing
If (onerror) {// verify whether onerror really exists
  onError(err.message);
}

//New writing method
onError?.( err.message); //  If onerror is undefined, there will be no exception
  • And expression
let nestedProp = obj?.['prop' + 'Name'];
  • Cannot be used for assignment
let object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
  • Accessing array elements
let arrayItem = arr?.[42];
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Nullish coalescing operator (??)

Null merge operator??)Is a logical operator when the operand on the left isnullperhapsundefinedReturns its right operand, otherwise returns the left operand.

AndLogical or operator(||Different, the logical or operator will be on the left, and the operand isFalse valueReturns the right operand. That is, if you use||To set default values for some variables, you may encounter unexpected behavior. For example, false (for example,''or0)Time. See the example below.

  • Basic use
const nullValue = null;
const emptyText = ""; //  Empty string, a false value, Boolean ("") = = = false
const someNumber = 42;

const valA = nullValue ?? " Default value of Vala ";
const valB = emptyText ?? " Default value of valb ";
const valC = someNumber ?? 0;

console.log(valA); // " Default value for Vala“
console.log(valB); // ""( Empty string is false but not null or undefined)
console.log(valC); // 42
  • And||contrast

Since 𞓜 is a Boolean logical operator, the operand on the left is cast to a Boolean value for evaluation. Any false values (0, ”, Nan, null, undefined) will not be returned. This leads to unpredictable consequences if you use 0, ” or Nan as valid values.

let myText = ''; // An empty string (which is also a falsy value)

let notFalsyText = myText || 'Hello world';
console.log(notFalsyText); // Hello world

let preservingFalsy = myText ?? 'Hi neighborhood';
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
  • short circuit

Similar to or and logical operators, when the left expression is notnullorundefinedThe right expression is not evaluated when.

Function a() {console.log ('function a called '); return undefined; }
Function b() {console.log ('function B called '); return false; }
Function c() {console.log ('function C called '); return "foo"; }

console.log( A() ?? C() );
//Print "function a called", "function C called" and "foo" successively
//A () returns undefined, so the expressions on both sides of the operator are executed

console.log( B() ?? C() );
//Print "function B called" and "false" successively
//B () returned false (neither null nor undefined)
//So the right expression is not executed
  • Not with||and&&share
null || undefined ?? " foo"; //  Throw syntax error
true || undefined ?? " foo"; //  Throw syntax error

//However, there is no problem if brackets are used to explicitly indicate the operation priority:
(null || undefined ) ?? " foo"; //  Return to "foo"
  • use?.Operator
let customer = {
  name: "Carl",
  details: { age: 82 }
};
let customerCity = customer?. city ?? " Dark city ";
console.log(customerCity); // “ "Dark city"
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

New features of ES10 (released in 2019)

Optional catchBinding (catch binding optional)

Allow when not in usecatchOmit binding in case of binding,catchThe parameters of can be ignored

  • Basic use
//Past
try {
} catch (error) {
}

//Now that syntax is supported, catch can not use the thrown error
try {
  // ...
} catch {
  // ...
}
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

JSON superset (JSON superset)

ECMAScript claims that JSON is a subset ofJSON.parse, but (well documented) this is incorrect because JSON strings can contain UN escaped U + 2028 line separator and U + 2029 paragraph separator characters, while ECMAScript strings cannot.

JSON syntax is defined byECMA-404Defined byRFC 7159Permanently fixed, but ecma-262DoubleStringCharacterandSingleStringCharacterProduction can be extended to allow non escaped U + 2028 line separator and U + 2029 paragraph separator characters.

Before es2019, it will generate errorsSyntaxError: Invalid or unexpected token

const PS = eval("'\u2029'");
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Symbol.prototype.description

descriptionIs a read-only property that returnsSymbolObject.

Objects can be created with an optional description and can be used for debugging, but not for accessing the symbol itself.Symbol.prototype.descriptionProperty can be used to read the description.

AndSymbol.prototype.toString()The difference is that it does not contain“Symbol()“The string for. Please refer to the example for details.

  • Basic use
Symbol('desc').toString();   // "Symbol(desc)"
Symbol('desc').description;  // "desc"
Symbol('').description;      // ""
Symbol().description;        // undefined

// well-known symbols
Symbol.iterator.toString();  // "Symbol(Symbol.iterator)"
Symbol.iterator.description; // "Symbol.iterator"

// global symbols
Symbol.for('foo').toString();  // "Symbol(foo)"
Symbol.for('foo').description; // "foo"
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Function.prototype.toStringcorrect

Returns a string representing the source code of the current function. Fixed that the return function contains comments (except arrow functions)

function sum /* comments... */(a, b) {
  return a + b;
}
console.log(sum.toString());
//Es2019
// function sum (a, b) {
//     return a + b;
// }

//After es2019
// function sum /* comments... */(a, b) {
//     return a + b;
// }

//Native code is not open
console.log(Math.abs.toString());
// function abs() { [native code] }

//Arrow functions do not contain comments
const arrowFunction /* comment */ = /* comment */ () => {};
console.log(arrowFunction.toString()); // () => {}

Object.fromEntries

Object.fromEntries(iterable)Method receives a list of key value pairs and returns a list with these key value pairsNew object

Parameters:iterablesimilarArrayMapOr something elseIterative protocolIteratable object.

Return: a new object with corresponding properties provided by the iteration object entry.

  • Basic use
// Map to Object
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
const obj = Object.fromEntries(map);
console.log(obj); // { foo: "bar", baz: 42 }

// Array to Object
const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }
const object1 = { a: 1, b: 2, c: 3 };

const object2 = Object.fromEntries(
  Object.entries(object1)
  .map(([ key, val ]) => [ key, val * 2 ])
);

console.log(object2);
// { a: 2, b: 4, c: 6 }
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Well-formed JSON.stringify

preventJSON.stringifyReturns malformed Unicode strings. Instead of returning unpaired proxy code points as a single utf-16 code unit, es2019 represents them with JSON escape sequences.

//Before
console.log(JSON.stringify("\uD800")); // "�"

//After es2019
console.log(JSON.stringify("\uD800")); // "\ud800"

String.prototype.{trimStart,trimEnd}

trimStart()Method removes spaces from the beginning of a string.trimLeft()Is an alias for this method. Method removes the continuous white space at the left end of the original string and returns a new string without directly modifying the original string itself.

trimEnd() Method removes white space characters from the end of a string.trimRight()Is an alias for this method. Method removes the continuous white space at the right end of the original string and returns it without directly modifying the original string itself.

  • Basic use
var str = "   foo  ";

console.log(str.length); // 8

STR = str.trimstart() // equivalent to STR = str.trimleft();
console.log(str.length); // 5
console.log(str);        // "foo  "

var str = "   foo  ";

alert(str.length); // 8

str = str.trimRight();  //  Or written as STR = str.trimend();
console.log(str.length); // 6
console.log(str);       // '   foo'
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years
Freshly baked, integrating the new features of es7-11 in recent years

Array.prototype.{flat,flatMap}

  1. flat

flatThe return method recursively traverses the array according to a specified depth, and combines all elements with the elements in the traversed sub array into a new array.

Syntax:var newArray = arr.flat([depth]

Input parameterdepth(optional): Specifies the structure depth for extracting nested arrays. The default value is 1.

Return: a new array containing all the elements in the array and subarray.

  • flatBasic use
var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

//With infinity, you can expand nested arrays of any depth
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

//Remove empty items from array
var arr5 = [1, 2, , 4, 5];
arr5.flat(); // [1, 2, 4, 5]
  1. flatMap

Method first uses the mapping function to map each element, and then compresses the result into a new array. It andmapWith a depth value of 1flatAlmost the same, butflatMapUsually the efficiency of merging into one method is slightly higher.

  • grammar
/**
    Parameters:
      callback
            可以生成一个新数组中的元素的函数,可以传入三个Parameters:
            currentValue
                The element currently being processed in the array
            Index optional
                Optional. The index of the current element being processed in the array.
            Array optional
                Optional. Called map array
        Thisarg optional
            Optional. The value of this used when executing the callback function.
            
    Return: a new array, in which each element is the result of the callback function, and the depth value of the structure is 1.        
 */
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])
  • Basic use
var arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]); 
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

//There is only one layer of flatted
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]
  1. compatibility

Freshly baked, integrating the new features of es7-11 in recent years
Freshly baked, integrating the new features of es7-11 in recent years

New features of es9 (released in 2018)

Lifting template literal restriction

Es2018 revision of illegal escape sequence:

Tagged template strings should allow nesting of languages that support common escape sequences (for exampleDSLsLaTeX)。 ECMAScript proposalTemplate literal revision(phase 4, to be integrated into ECMAScript 2018 standard) remove the syntax restrictions on ECMAScript escaping sequences in tagged template strings.

function latex(str) { 
 return { "cooked": str[0], "raw": str.raw[0] }
} 

latex`\unicode`

//Older versions es2016 or earlier
// SyntaxError: malformed Unicode character escape sequence

// es2018
// { cooked: undefined, raw: "\\unicode" }
  • It should be noted that this escape sequence limits the removal of the tagged template literal only, and does not include the unlabeled template literal:
let bad = `bad escape sequence: \unicode`; //  Unexpected syntax error: invalid Unicode escape sequence

regular expression \s or (dotAll)

Regular expression midpoint.Match any single character except carriage return, marksChange this behavior to allow line terminators

/foo.bar/.test('foo\nbar');
// → false

/foo.bar/s.test('foo\nbar');
// → true
  • dotAlldotAllProperty indicates whether to use it together in regular expressions“s“Modifier (introduces the / s modifier so that. Can match any single character).dotAllIs a read-only property that belongs to a single regular expression instance.
const re = /foo.bar/s; // Or, `const re = new RegExp('foo.bar', 's');`.
re.test('foo\nbar');
// → true
re.dotAll
// → true
re.flags
// → 's'
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Regexp named capture groups

Es2018 allows named capture groups to use symbols?<name>, capture parentheses when opening(Name immediately after, for example:

Any named group that fails to match will be returnedundefined

  • exec
let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result = re.exec('2015-01-02');
// result.groups.year === '2015';
// result.groups.month === '01';
// result.groups.day === '02';

// result[0] === '2015-01-02';
// result[1] === '2015';
// result[2] === '01';
// result[3] === '02';
  • replace
let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result = '2015-01-02'.replace(re, '$<day>/$<month>/$<year>');
// result === '02/01/2015'

Rest/Spread Properties

Es2015 introducesRest parameterandExtension operator。 Three points (…) are only used for arrays. The rest parameter syntax allows us to represent an indefinite number of parameters as an array.

// es2015 
restFunc(1, 2, 3, 4, 5);

function restFunc(arg1, arg2, ...arg3) {
  // arg1 = 1
  // arg2 = 2
  // arg3 = [3, 4, 5]
}

//Expand properties
const arr = [1, 4, -1, 5, 9];
console.log(Math.max(...values)); // 9

Es2018 provides the same rest parameters and (…) expansion operators as arrays for object deconstruction

  • Rest attribute
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x; // 1
y; // 2
z; // { a: 3, b: 4 }
  • Expand properties
let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }

Regexp lookbehind assertions

  • Forward assertion(?<=...), they ensure that the schema contained in it precedes the schema after the declaration
//Matching amount
/(?<=$)\d+(\.\d*)?/.exec('$10.53');
// [10.53 ...]
/(?<=$)\d+(\.\d*)?/.exec('¥10.53');
// null
  • Reverse assertion(?<!...)On the other hand, make sure that the pattern does not precede the pattern after the assertion
/(?<!$)\d+(?:\.\d*)/.exec('$10.53')
// [0.53 ...]

/(?<!$)\d+(?:\.\d*)/.exec('¥10.53')
// [10.53 ...]

Escape Unicode properties in regular expressions (regexp Unicode property escapes)

Before es2018, local access to Unicode character properties in regular expressions is not allowed.

Es2018 adds Unicode attribute escape – in the form of\p{...}and\P{...}, using tags in regular expressionsu(Unicode) settings, in\pIn the block, you can set the attributes to be matched in the form of key value pairs instead of specific contents.

const regex = /^\p{Decimal_Number}+$/u;
regex.test('𝟏𝟐𝟑𝟜𝟝𝟞𝟩𝟪𝟫𝟬𝟭𝟮𝟯𝟺𝟻𝟼');
// → true

const regex = /^\P{Decimal_Number}+$/u;
regex.test('Իմ օդաթիռը լի է օձաձկերով');
// → true

const regex = /^\p{Number}+$/u;
regex.test('²³¹¼½¾𝟏𝟐𝟑𝟜𝟝𝟞𝟩𝟪𝟫𝟬𝟭𝟮𝟯𝟺𝟻𝟼㉛㉜㉝ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿ');
// → true

Promise.prototype.finally

finally()Method returns aPromise。 At the end of the promise, the specified callback function will be executed regardless of whether the result is fully or rejected. This is inPromiseCode that needs to be executed after successful completion provides a way.

This avoids the need for the same statement inthen()andcatch()Write once in each.

be careful:stayfinallyCallback in progressthrow(or return rejected promise) willthrow()Reject the new promise for the specified reason

  • finally()Although with.then(onFinally, onFinally)They are similar in that:

    • When calling an inline function, you do not need to declare the function multiple times or create a variable for the function to save it.
    • Because I can’t knowpromiseThe final state, sofinallyThe callback function of does not receive any parameters. It is only used for execution regardless of the final result.
    • AndPromise.resolve(2).then(() => {}, () => {})(the resolved result isundefined)Different,Promise.resolve(2).finally(() => {})The result of resolved is2
    • Again,Promise.reject(3).then(() => {}, () => {})(the resolved result isundefined), Promise.reject(3).finally(() => {})The result of rejected is3
  • Basic use
let isLoading = true;

fetch(myRequest).then(function(response) {
    var contentType = response.headers.get("content-type");
    if(contentType && contentType.includes("application/json")) {
      return response.json();
    }
    throw new TypeError("Oops, we haven't got JSON!");
  })
  .then(function(json) { /* process your JSON further */ })
  .catch(function(error) { console.log(error); })
  .finally(function() { isLoading = false; });
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Asynchronous iteration

Es2018 introduces asynchronous iteratorsfor-await-of, so thatawaitCan andfor...ofLoop to run asynchronous operations in a serial manner.

for await...ofsentenceAn iteration loop is created on asynchronous or synchronous iteratible objects, includingStringArrayArray-Like object (e.gargumentsperhapsNodeList),TypedArrayMapSetAnd custom asynchronous or synchronous iteratable objects. It calls the custom iteration hook and executes the statement for the value of each different attributeimageawaitLike an expression, this statement can only be used inasync functionInternal use.

  • Before es2018, error scenario cases

stayasync/awaitAt some point, you may try to call asynchronous functions in the synchronous loop.

//The following method loop itself is still synchronized and will be called before the internal asynchronous function is completed
async function process(array) {
  for (let i of array) {
    await doSomething(i);
  }
}
async function process(array) {
  array.forEach(async i => {
    await doSomething(i);
  });
}
  • Basic use
async function process(array) {
  for await (let i of array) {
    doSomething(i);
  }
}
  • Iterative asynchronous iteratable object
var asyncIterable = {
  [Symbol.asyncIterator]() {
    return {
      i: 0,
      next() {
        if (this.i < 3) {
          return Promise.resolve({ value: this.i++, done: false });
        }

        return Promise.resolve({ done: true });
      }
    };
  }
};

(async function() {
   for await (num of asyncIterable) {
     console.log(num);
   }
})();

// 0
// 1
// 2
  • Iterative asynchronous generator
async function* asyncGenerator() {
  var i = 0;
  while (i < 3) {
    yield i++;
  }
}

(async function() {
  for await (num of asyncGenerator()) {
    console.log(num);
  }
})();
// 0
// 1
// 2
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

New features of es8 (released in 2017)

Object.values/Object.entries

  • Object.values

Object.values()Method returns an array of all enumerable attribute values of a given object, and the order and use of the valuesfor...inThe order of loops is the same (the difference is that the for in loop enumerates the attributes in the prototype chain).

  • Object.entries

The object. Entries () method returns an array of key value pairs of enumerable properties of a given object, which are arranged and used[for…in`](https://developer.mozilla.org…The order returned when the loop traverses the object is the same (the difference is that the for in loop also enumerates the attributes in the prototype chain).

  • Basic use
var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years
Freshly baked, integrating the new features of es7-11 in recent years

String padding

  • String.prototype.padStart

padStart()Method fills the current string with another string (repeated multiple times if necessary) so that the resulting string reaches the given length. Fills from the left side of the current string.

  • String.prototype.padEnd

padEnd()Method will fill the current string with a string (repeat filling if necessary) and return the filled string of the specified length. Populates from the end (right) of the current string.

  • grammar
/** 
    *Parameters
    * 
    *Targetlength: the target length to fill in the current string. If this value is less than the length of the current string, the current string itself is returned.
     *Padstring (optional): fills the string. If the string is too long and the length of the filled string exceeds the target length, only the leftmost part will be retained, and other parts will be truncated. The default value of this parameter is "" (U + 0020).
     */
str.padStart(targetLength [, padString])
str.padEnd(targetLength [, padString])
  • Basic use
'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc"

'abc'.padEnd(10);          // "abc       "
'abc'.padEnd(10, "foo");   // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1);           // "abc"
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years
Freshly baked, integrating the new features of es7-11 in recent years

Object.getOwnPropertyDescriptors

Object.getOwnPropertyDescriptors()Method is used to get the descriptors of all its own properties of an object.

Input parameters: any object

Return: the descriptor of all self attributes of the specified object. If there are no self attributes, an empty object is returned.

  • Basic use
//The object. Assign () method can only copy the enumerable properties of the source object. At the same time, the properties of the properties cannot be copied during copying. In addition, the accessor properties will be converted into data properties, and the prototype of the source object cannot be copied. This method can be combined with the object. Create () method to achieve the above.
Object.create(
  Object.getPrototypeOf(obj), 
  Object.getOwnPropertyDescriptors(obj) 
);
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Trailing comma in function parameter lists and calls is allowed

During this change to the code managed by the version control system (GIT, subversion, mercurial, etc.), the unconventional / comment code history information in lines 3 and 9 will be updated to point to the person who added the comma (rather than the person who originally added the parameter).

1: function clownPuppiesEverywhere(
 2:   param1,
 3:   param2, // updated to add a comma
 4:   param3  // updated to add new parameter
 5: ) { /* ... */ }
 6: 
 7: clownPuppiesEverywhere(
 8:   'foo',
 9:   'bar', // updated to add a comma
10:   'baz'  // updated to add new parameter
11: );

To help alleviate this problem, some other languages (Python, D, hack, etc… and possibly others…) have added syntax support to allow comma endings in these parameter lists. This allows code providers to always end parameter additions with a trailing comma in one of these per line parameter lists without having to worry about code attribution

 1: function clownPuppiesEverywhere(
 2:   param1,
 3:   param2, // Next parameter that's added only has to add a new line, not modify this line
 5: ) { /* ... */ }
 6: 
 7: clownPuppiesEverywhere(
 8:   'foo',
 9:   'bar', // Next parameter that's added only has to add a new line, not modify this line
11: );

Note that this recommendation is syntax only and does not make any semantic changes, so the presence of trailing commas has no impact on things like<<function>>.length

Async functions

The async function usesasyncKeyword declared function. The async function isAsyncFunctionAn instance of the constructor, and it is allowed to useawaitkeyword.asyncandawaitKeywords allow us to write in a more concise wayPromiseAsynchronous behavior without deliberate chainingpromise

Async function may contain 0 or moreawaitexpression. Await expression will suspend the execution process of the entire async function and transfer its control. It will resume the process only after the promise based asynchronous operation it is waiting for is cashed out or rejected. The resolve value of promise is treated as the return value of the await expression. useasync / awaitKeyword can be used in asynchronous codetry / catchCode block.

awaitKeyword is only valid within async function. If you use it outside the body of the async function, you will throw a syntax errorSyntaxError

async/awaitThe purpose of is to simplify the syntax required when using promise based APIs.async/awaitThe behavior is like using a generator with promise.

  • Basic use
async function foo() {
   return 1
}
//Equivalent to
function foo() {
   return Promise.resolve(1)
}

//The function body of async function can be regarded as separated by 0 or more await expressions.
//It runs synchronously from the first line of code to (and including) the first await expression (if any).
//In this case, an async function without await expression will run synchronously.
//However, if there is an await expression in the function body, the async function must execute asynchronously.
async function foo() {
   await 1
}
//Equivalent to
function foo() {
   return Promise.resolve(1).then(() => undefined)
}
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Shared memoryandAtomics(Shared memory and atomics)

Shared memoryandAtomics: a new constructor is introducedSharedArrayBufferAnd namespace objects with helper functionsAtomics

  • SharedArrayBufferObject is used to represent a generic, fixed length raw binary data buffer, similar toArrayBufferObjects that can be used to create views on shared memory. AndArrayBufferThe difference is,SharedArrayBufferCannot be separated.

To put oneSharedArrayBufferObject is shared from one user agent to another user agent (the main process of another page or one of the current page)worker)To achieve shared memory, we need to usepostMessageStructured cloning algorithm(structured cloning )。

Structured cloning algorithmReceive is mapped to a newSharedArrayBuffersOn objectSharedArrayBuffersObject andTypedArraysObject. Under these two mappings, this newSharedArrayBufferThe object is passed to the receiving function of the target user agent, resulting in a new private object in the target user agentSharedArrayBufferObject (asArrayBufferSame). However, these twoSharedArrayBufferThe shared data block pointed to by the object is actually the same, and the side effect of one block in one agent will eventually lead to the visibility of another agent.

These atomic operations belong toAtomicsmodular. Unlike general global objects,AtomicsIs not a constructor, so it cannot be usednewOperator, nor can it be called directly as a function.AtomicsAll properties and methods of are static (andMathObject).

New features of ES7 (released in 2016)

Array.prototype.includes

includes()Method is used to determine whether an array contains a specified value. If it does, it returns true, otherwise it returns false.

  • grammar
/**
    *Valuetofind: the element value to find.
    *Fromindex (optional): find valuetofind from the fromindex index. If it is a negative value, the search starts from the index of array.length + fromindex in ascending order (even if the absolute value of fromindex jumps forward by one index from the end, and then searches backward). The default is 0.
    *Return: returns a Boolean value. If it is found in the array (if fromindex is passed in, it means it is found in the index range specified by fromindex), it returns true.
    */
arr.includes(valueToFind[, fromIndex])
  • Basic use
[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
  • IffromIndex If it is negative, the calculated index will be used as the start of the searchsearchElementThe location of the. If the calculated index is less than 0, the entire array is searched.
//The calculated index is less than 0
// array length is 3
// fromIndex is -100
// computed index is 3 + (-100) = -97
var arr = ['a', 'b', 'c'];

arr.includes('a', -100); // true
arr.includes('b', -100); // true
arr.includes('c', -100); // true
arr.includes('a', -2); // false
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

Exponentiation (* *) (expansion operator)

Exponentiation operator(**)Returns the result of adding the first operand to the power of the second operand. It is equivalent toMath.pow, except that it also accepts bigints as operands.

The exponentiation operator is yesRight associative: a ** b ** cbe equal toa ** (b ** c).

  • Basic use
2 ** 3   // 8
3 ** 2   // 9
3 ** 2.5 // 15.588457268119896
10 ** -1 // 0.1
NaN ** 2 // NaN

//Right binding
2 ** 3 ** 2   // 512
2 ** (3 ** 2) // 512
(2 ** 3) ** 2 // 64

//Combined with unary operator
-(2 ** 2) // -4
(-2) ** 2 // 4
  • In JavaScript, you can’t write an ambiguous exponentiation expression. That is, you can’t immediately put a unary operator(+/-/~/!/delete/void/typeof)Before the cardinality, this will only lead to a syntax error.
-2 ** 2; 
// 4 in Bash, -4 in other languages. 
// This is invalid in JavaScript, as the operation is ambiguous. 

-(2 ** 2); 
// -4 in JavaScript and the author's intention is unambiguous. 
  • compatibility

Freshly baked, integrating the new features of es7-11 in recent years

reference resources