Let’s see some new JavaScript features coming in ES2020 or ECMAScript 2020 or ES11 standard. ES2020 brings tons of sweet improvements, let’s see all of them real quick here!

Many people apprehend that there’s a typical procedure for Javascript’s latest releases and a committee behind that. during this post, i’ll justify who makes the ultimate appeal any new specification, what’s the procedure for it, and what is new in ES2020.

The language specification that drives JavaScript is named ECMAScript. there’s a team behind that referred to as Technical Committee thirty****-****nine [TC39] that reviews each specification before adopting.

Every modification goes through a method with stages of maturity.

Stage 0: Ideas/Strawman
Stage 1: Proposals
Stage 2: Drafts
Stage 3: Candidates
Stage 4: Finished/Approved

A feature that reaches Stage four can presumably be a part of the language specification.

In this article, we’re going to review some of the latest and greatest features coming with ES2020.

Let’s dive into the items that are recently into the specification underneath ES2020.

Installation

Since many people don’t think to update their browsers to make their developer’s lives easier, we’ll need to use babel to get started using features that are not available across the board for users. For simplicity’s sake, I’ll use the Parcel bundler to get everything running as quickly as possible.

$ yarn add parcel-bundler

"scripts": {
  "start": "parcel index.html"
},

Sadly, at the time of this writing we’re too far ahead of our time and there doesn’t seem to be a working preset for ES2020. If you throw these in a .babelrc file and save, Parcel should handle installing everything for you.

{
  "plugins": [
    "@babel/plugin-proposal-nullish-coalescing-operator",
    "@babel/plugin-proposal-optional-chaining",
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-private-methods",
    "@babel/plugin-syntax-bigint"
  ]
}

Array.prototype

Array.prototype.flat() planned to flatten arrays recursively up to the required depth and returns a replacement array.

Syntax: Array.prototype.flat(depth)
depth — Default worth one, Use time to flatten all nested arrays.

const numbers = [1, 2, [3, 4, [5, 6]]];
// Considers default depth of 1
numbers.flat(); 
> [1, 2, 3, 4, [5, 6]]
// With depth of 2
numbers.flat(2); 
> [1, 2, 3, 4, 5, 6]
// Executes two flat operations
numbers.flat().flat(); 
> [1, 2, 3, 4, 5, 6]
// Flattens recursively until the array contains no nested arrays
numbers.flat(Infinity)
> [1, 2, 3, 4, 5, 6]

Array.prototype.flatMap() maps every part employing a mapping perform and flattens the result into a replacement array. It’s clone of the map operation followed by a flat of depth one.

Syntax: Array.prototype.flatMap(callback)
callback: perform that produces a part of the new Array.

const numbers = [1, 2, 3];
numbers.map(x => [x * 2]);
> [[2], [4], [6]]
numbers.flatMap(x => [x * 2]);
> [2, 4, 6]

Private Class Variables

One of the main purposes of classes is to contain our code into more reusable modules. Because you’ll create a class that’s used in many different places you may not want everything inside it to be available globally.

Now, by adding a simple hash symbol in front of our variable or function we can reserve them entirely for internal use inside the class.

class Message {
  #message = "Howdy"

  greet() { console.log(this.#message) }
}

const greeting = new Message()

greeting.greet() // Howdy
console.log(greeting.#message) // Private name #message is not defined

Object.fromEntries

Object.fromEntries performs the reverse of Object.entries . It transforms a listing of key-value pairs into AN object.

Syntax: Object.fromEntries(iterable)
iterable: AN iterable like Array or Map or objects implementing the iterable protocol

const records = [['name','Mathew'], ['age', 32]];
const obj = Object.fromEntries(records);
> { name: 'Mathew', age: 32}
Object.entries(obj);
> [['name','Mathew'], ['age', 32]];

Promise.allSettled

When we’re working with multiple promises, especially when they are reliant on each other, it could be useful to log what’s happening to each to debug errors. With Promise.allSettled, we can create a new promise that only returns when all of the promises passed to it are complete. This will give us access to an array with some data on each promise.

const p1 = new Promise((res, rej) => setTimeout(res, 1000));

const p2 = new Promise((res, rej) => setTimeout(rej, 1000));

Promise.allSettled([p1, p2]).then(data => console.log(data));

// [
//   Object { status: "fulfilled", value: undefined},
//   Object { status: "rejected", reason: undefined}
// ]

BigInt

We won’t go into the technical details, but because of how JavaScript handles numbers, when you go high enough things start to get a bit wonky. The largest number JavaScript can handle is 2^53, which we can see with MAX_SAFE_INTEGER.

const max = Number.MAX_SAFE_INTEGER;

console.log(max); // 9007199254740991

Anything above that and things start to get a little weird…

console.log(max + 1); // 9007199254740992
console.log(max + 2); // 9007199254740992
console.log(max + 3); // 9007199254740994
console.log(Math.pow(2, 53) == Math.pow(2, 53) + 1); // true

We can get around this with the new BigInt datatype. By throwing the letter ‘n’ on the end we can start using and interacting with insanely large numbers. We’re not able to intermix standard numbers with BigInt numbers, so any math will need to be also done with BigInts.

const bigNum = 100000000000000000000000000000n;

console.log(bigNum * 2n); // 200000000000000000000000000000n

String.prototype.

trimStart() removes whitespace from the start of a string and trimEnd() removes whitespace from the tip of a string.

const greeting = ` Hello Javascript! `;
greeting.length;
> 19
greeting = greeting.trimStart();
> 'Hello Javascript! '
greeting.length;
> 18
greeting = 'Hello World!   ';
greeting.length;
> 15
greeting = greeting.trimEnd();
> 'Hello World!'
greeting.length;
> 12

Nullish Coalescing Operator

Because JavaScript is dynamically typed, you’ll need to keep JavaScript’s treatment of truthy/falsy values in mind when assigning variables. If we have a object with some values, sometimes we want to allow for values that are technically falsy, like an empty string or the number 0. Setting default values quickly gets annoying since it’ll override what should be valid values.

let person = {
  profile: {
    name: "",
    age: 0
  }
};

console.log(person.profile.name || "Anonymous"); // Anonymous
console.log(person.profile.age || 18); // 18

Instead of double pipes we can use the double question marks operator to be a bit more type strict, which only allows the default when the value is null or undefined.

console.log(person.profile.name ?? "Anonymous"); // ""
console.log(person.profile.age ?? 18); // 0

Optional Chaining Operator

Similar to the nullish coalescing operator, JavaScript may not act how we want when dealing with falsy values. We can return a value if what we want is undefined, but what if the path to it is undefined?

By adding a question mark before our dot notation we can make any part of a value’s path optional so we can still interact with it.

let person = {};

console.log(person.profile.name ?? "Anonymous"); // person.profile is undefined
console.log(person?.profile?.name ?? "Anonymous");
console.log(person?.profile?.age ?? 18);

Dynamic Import

If you had a file full of utility functions, some of them may rarely be used and importing all of their dependencies could just be a waste of resources. Now we can use async/await to dynamically import our dependencies when we need them.

This will not work with our current Parcel setup, since we’re using imports which will only work in a Node.js environment.

const add = (num1, num2) => num1 + num2;

export { add };

const doMath = async (num1, num2) => {
  if (num1 && num2) {
    const math = await import('./math.js');
    console.log(math.add(5, 10));
  };
};

doMath(4, 2);

Conclusion

Now you’re ready to start amazing or perhaps confusing your coworkers with JavaScript features that aren’t even in most browsers, yet (unless they are if you are reading this from the future 😉).

#javascript #es6 #web-development #angular #node-js

What's New in JavaScript ES2020?
34.30 GEEK