Development

Best five awesome ES6 (ECMAScript) features of 2020!

Best five awesome ES6 (ECMAScript) features of 2020!

According to Wikipedia, ECMAScript is a scripting language specification standardized by Ecma International. It was created to standardize JavaScript to help foster multiple independent implementations.

ES6 brings forth a massive wave of new goodies and the browser vendors have worked hard over the past year to get those language updates into their browser.

While there are big updates, some of the smaller language updates have put a massive smile on my face; the following are six of my favorite new additions within the JavaScript language!

1.  Object [key] setting syntax:

An object can be created with figure brackets {…} with an optional list of properties. A property is a “key: value” pair, where key is a string (also called a “property name”), and value can be anything.

Here is some example:

// *Very* reduced example
let myKey = 'key3';
let obj = {
    key1: 'One',
    key2: 'Two'
};
obj[myKey] = 'Three';

At best this pattern is inconvenient and at worst it’s confusing and ugly.  ES6 provides developers a way out of this mess:

let myKey = 'variableKey';
let obj = {
    key1: 'One',
    key2: 'Two',
    [myKey]: 'Three' /* yay! */
}

Wrapping the variable key in [] allows developers to get everything done within one statement!

2.  Arrow Functions:

Arrow functions – also called “fat arrow” functions, from CoffeeScript (a transcompiled language) — are a more concise syntax for writing function expressions. They utilize a new token, =>, that looks like a fat arrow. Arrow functions are anonymous and change the way this binds in functions.

You don’t need to have kept up with every ES6 change to know about arrow functions — they’ve been the source of much talk and some confusion (at least initially) to JavaScript developers.  While I could write multiple blog posts to explain each facet of the arrow function, I want to point out how arrow functions provide a method for condensed code for simple functions:

// Adds a 10% tax to total
let calculateTotal = total => total * 1.1;
calculateTotal(10) // 11

// Cancel an event -- another tiny task
let brickEvent = e => e.preventDefault();
document.querySelector('div').addEventListener('click', brickEvent);

No function or return keywords, sometimes not even needing to add () — arrow functions are a great coding shortcut for simple functions.

3.  find/findIndex:

JavaScript gives developers Array.prototype.indexOf to get the index of a given item within an array, but indexOf doesn’t provide a method to calculate the desired item condition; you also need to search for an exact known value.  Enter find and findIndex — two methods for searching an array for the first match of a calculated value:

let ages = [12, 19, 6, 4];

let firstAdult = ages.find(age => age >= 18); // 19
let firstAdultIndex = ages.findIndex(age => age >= 18); // 1

find and findIndex, through allowing a calculated value search, also prevent unnecessary side effects and looping through possible values!

4.  The Spread Operator: ... :

The spread operator signals that an array or iterable object should have its contents split into separate arguments within a call.  A few examples:

// Pass to function that expects separate multiple arguments
// Much like Function.prototype.apply() does
let numbers = [9, 4, 7, 1];
Math.min(...numbers); // 1

// Convert NodeList to Array
let divsArray = [...document.querySelectorAll('div')];

// Convert Arguments to Array
let argsArray = [...arguments];

The awesome added bonus is being able to convert iterable objects (NodeListarguments, etc.) to true arrays — something we’ve used Array.from or other hacks to do for a long time.

5.  Template Literals:

Multiline strings within JavaScript were originally created by either concatenation or ending the line with a \ character, both of which can be difficult to maintain.   Many developers and even some frameworks started abusing <script> tags to encapsulate multiline templates, others actually created the elements with the DOM and used outerHTML to get the element HTML as a string.

ES6 provides us template literals, whereby you can easily create multiline strings using backticks characters:

// Multiline String
let myString = `Hello

I'm a new line`; // No error!

// Basic interpolation
let obj = { x: 1, y: 2 };
console.log(`Your total is: ${obj.x + obj.y}`); // Your total is: 3

Of course, template literals allow you to create more than multiline strings, like simple to advanced interpolation, but just the ability to create multiline strings elegantly puts a smile on my face.

Also, read this article:

Best 5 Vscode extensions for react developer in 2020.

Leave a comment

Your email address will not be published. Required fields are marked *