JS TutorialLesson #143

ECMAScript 2020

ECMAScript 2020 is supported in all modern browsers since April 2021.

New Features in JavaScript 2020

FeatureDescription
BigIntStores values too big to store in a JavaScript number
String matchAll()Searchs for all occurrences of a string in a string
Promise.allSettled()Takes promises as input and returns a single promise
Dynamic ImportLoads JavaScript modules at runtime
globalThisRefers to the global object independent of code environment
import.metaReturns an object indicating the base URL of a module
Namespace ExportsExport a full namespace from a module without having to import it first

New JavaScript Operators in 2020

OperDescription
??Nullish coalescing returns the first argument not nullish
?.Optional chaining returns undefined if an object is undefined or null
&&=Logical AND assignment assigns the second value if the first value is true
[\\=](js_2020.asp?#mark_assign_logical_or)Logical OR assignment assigns the second value if the first value is false
??=Nullish coalescing assignment assigns the second value if the first value is undefined or null

Browser Support

ECMAScript 2020 is supported in all modern browsers since April 2021.

Chrome 80Edge 80Firefox 80Safari 14.1Opera 67
Feb 2020Feb 2020Aug 2020Apr 2021Mar 2020

JavaScript BigInt

JavaScript BigInt variables are used to store big integer values that are too big to be represented by a a normal JavaScript Number.

JavaScript integers are only accurate up to about 15 digits.

Integer Example

Example Code

javascript
Try it Yourself
let x = 999999999999999;

let y = 9999999999999999; // too big

To create a BigInt, append n to the end of an integer or call BigInt():

Example

Example Code

javascript
Try it Yourself
let x = 1234567890123456789012345n;

let y = BigInt(1234567890123456789012345)

The JavaScript typeof a BigInt is "bigint":

Example

Example Code

javascript
Try it Yourself
let x = BigInt(999999999999999);

let type = typeof x;

JavaScript String matchAll()

Before ES2020 there was no string method that could be used to search for all occurrences of a string in a string.

Example

Example Code

javascript
Try it Yourself
const iterator = text.matchAll("Cats");

If the parameter is a regular expression, the global flag (g) must be set set, otherwise a TypeError is thrown.

Example

Example Code

javascript
Try it Yourself
const iterator = text.matchAll(/Cats/g);

If you want to search case insensitive, the insensitive flag (i) must be set:

Example

Example Code

javascript
Try it Yourself
const iterator = text.matchAll(/Cats/gi);
ES2021 introduced the string method replaceAll().

The Nullish Coalescing Operator (??)

The ?? operator returns the first operand if it is not nullish. Otherwise it returns the second.

The ?? operator returns the second operand if the first operand is nullish.

Nullish is a word for describing null or undefined.

The ?? operator is used to provide default values and is distinct from the logical OR operator || because it only treats null and undefined as "nullish" and ignores other "falsy" values like 0 or an empty string.

Example

Example Code

javascript
Try it Yourself
let name = null;

let text = "missing";

let result = name ?? text;

The Optional Chaining Operator (?.)

The Optional Chaining Operator returns undefined if an object property is undefined or null (instead of throwing an error).

Example

Example Code

javascript
Try it Yourself
const car = {type:"Fiat", model:"500", color:"white"};

let name = car?.name;

Optional chaining not only works on object properties, but also on function calls and arrays.

Function Calls

Use CaseSyntaxBehavior
Safe function callobj.method?.()Returns undefined if method does not exist
Return handlinglet x = fn?.()x is undefined if fn does not exist

Arrays

Use CaseSyntaxReturns
Safe element accessarr?.[2]undefined if arr is null or undefined
Safe property on elementarr?.[1]?.nameReturns undefined safely
Safe method callarr?.map(fn)Returns undefined if arr does not exist
Default value fallbackarr?.[0] ?? "N/A"Returns "N/A" if arr or element is missing

The &&= Operator

The Logical AND Assignment Operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

Example Code

javascript
Try it Yourself
let x = 10;

x &&= 5;

The ||= Operator

The Logical OR Assignment Operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

Example Code

javascript
Try it Yourself
let x = 10;

x ||= 5;

The ??= Operator

The Nullish Coalescing Assignment Operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

Example Code

javascript
Try it Yourself
let x;

x ??= 10;

JavaScript Promise.allSettled()

The Promise.allSettled() method returns a single Promise from a list of promises.

Example

Example Code

javascript
Try it Yourself
// Create a Promise

const myPromise1 = new Promise((resolve, reject) => {

  setTimeout(resolve, 200, "King");

});

// Create another Promise

const myPromise2 = new Promise((resolve, reject) => {

  setTimeout(resolve, 100, "Queen");

});

// Settle All

Promise.allSettled([myPromise1, myPromise2]).then((results) =>

  results.forEach((x) => myDisplay(x.status)),

);
Promise.allSettled() means "Just run all promises. I don't care about the results".

JavaScript Dynamic Import

Dynamic Import is a way to load JavaScript modules at runtime, rather than at the start of your program.

Syntax

Example Code

javascript
Try it Yourself
import("./module.js")
  • The argument must be a string or expression that resolves to a path
  • You must run the import inside a module script ( )

Unlike static imports (which must appear at the top of a file), dynamic imports can be used anywhere - inside functions, conditionals, event handlers, etc.

TypeExampleWhen Loaded
Staticimport { add } from './math.js';At load time
Dynamicconst math = await import('./math.js');When needed

JavaScript Global This

globalThis provides a standard way to access the global object, regardless of the environment your the code runs in: In the browser, Node.js, in a Web Worker, or another JS runtime.

The global object is the top-level object in a JavaScript environment: - In browsers, it is window. - In Node.js, it is global. - In Web Workers, it is self. Many environments have their own name for the this object. This caused compatibility issues for code meant to run everywhere.

globalThis was introduced in ECMAScript 2020 (ES11) to solve that problem. It is a unified reference to the global object, no matter the environment.

Examples

Example Code

javascript
Try it Yourself
globalThis === window); // true in browsers

globalThis === global); // true in Node.js

Previously, developers had to use workarounds like:

Example

Example Code

javascript
Try it Yourself
const getGlobal = function() {

  if (typeof self !== 'undefined') return self;

  if (typeof window !== 'undefined') return window;

  if (typeof global !== 'undefined') return global;

  throw new Error('Cannot find global object');

};

With globalThis, that is no longer needed.


JavaScript import.meta

import.meta returns an object containing the base URL of a module.

Example

Example Code

javascript
Try it Yourself
const myObject = import.meta;

Module Namespace Exports

With module namespace exports, you can re-export an entire namespace from your own module, without having to import it first.

Example

Example Code

javascript
Try it Yourself
// re-export all named exports directly

export * from "./utils.js";

// consumers can use:

import { add } from "./math.js";

Interactive Code Examples

Integer Example

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let x = 999999999999999;

let y = 9999999999999999; // too big

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let x = 1234567890123456789012345n;

let y = BigInt(1234567890123456789012345)

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let x = BigInt(999999999999999);

let type = typeof x;

JS Example 4

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const iterator = text.matchAll("Cats");

JS Example 5

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const iterator = text.matchAll(/Cats/g);

JS Example 6

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const iterator = text.matchAll(/Cats/gi);