What is ECMAScript?
ECMAScript 6 or ES6 is the latest version of JavaScript. It is standardized by the ECMA International standards organization in the ECMA-262 and ECMA-402 specifications.
Why ES6?
The main goal of ES6 (or officially, ECMA-262) has been to provide a better support for creating larger applications and libraries in a simplified manner. This means a more mature syntax, new shortcuts to make coding easier, and also new methods, keywords, data types, and other enhancements.
Features:
The features have varying degrees of complexity and are useful in both simple scripts and complex applications. ES6 has a lot to offer, but let us look at some hand-picked and useful ES6 features that can be used in our everyday JavaScript coding.
Variables
LET
ES6 introduces the new let keyword that allows us to declare local variables in the scope of a block, such as a statement, an expression, or a(n inner) function. The subtle difference between let and var lies in scope. While var results in a variable with the surrounding function as its scope, the scope of a variable declared using let is only the block it is in.
function order(x, y) { if (x > y) { let tmp = x; x = y; y = tmp; } console.log(tmp===x); // ReferenceError: tmp is not defined return [x, y]; }
CONST
The new const keyword makes it possible to declare constants, also known as immutable variables, to which we cannot reassign new content later.
const myConst = 1; myConst = 2 // Error const myConst; // Error
However, immutable variables are not always fully immutable in ES6. We can still change object properties or array members.
const objConst = {myProperty: 6}; console.log(objConst.myProperty); 6 objConst.myProperty = 18; console.log(objConst.myProperty); 18 // Works const arrayConst = [12, 14, 16]; console.log(arrayConst[0]); 12 arrayConst[0] = 22; console.log(arrayConst[0]); 22 // Works
Arrow Functions
ES6 facilitates how we write anonymous functions, as we can completely omit the function keyword. We only need to use the new syntax for arrow functions, the => arrow sign (fat arrow), that provides us with a great shortcut.
// 1. One parameter in ES6 let sum = (a, b) => a + b; // in ES5 var sum = function(a, b) { return a + b; }; // 2. Without parameters in ES6 let randomNum = () => Math.random(); // in ES5 var randomNum = function() { return Math.random(); }; // 3. Without return in ES6 let message = (name) => alert("Hi " + name + "!"); // in ES5 var message = function(yourName) { alert("Hi " + yourName + "!"); };
Not only do arrow functions mean fewer characters to type, but they also behave differently from regular functions. Arrow functions lexically bind the this value to the current scope. This means that we can easily reuse the this keyword in an inner function.
// ES5 Hack to use the "this" keyword in an inner function var self = this $('.btn').click(function(event){ self.sendData() }) // ES6, the same inner function now can use its own "this" $('.btn').click((event) =>{ this.sendData() })
Spread Operator
The spread operator (…) is a very convenient syntax to expand elements of an array in specific places, such as arguments in function calls.
let myArray = [1, 2, 3]; let newArray = [...myArray, 4, 5, 6]; console.log(newArray); // 1, 2, 3, 4, 5, 6
We can also use the spread operator in function calls in which we want to pass in arguments from an array:
let myArray = [1, 2, 3]; function sum(a, b, c) { return a + b + c; } console.log(sum(...myArray)); // 6
Parameters
DEFAULT VALUES
In ES6, we can add default values to the parameters of a function. This means that if we don’t pass in arguments in the function call, the default parameters will be used. In ES5, the default values of parameters are always set to undefined.
//ES6 function doSomething(x, y = 2) { return x * y; } doSomething(5); // 10 doSomething(5, undefined); // 10 doSomething(5, 3); // 15 //ES5 function doSomething(x, y) { y = y === undefined ? 2 : y; return x * y; }
REST PARAMETERS
ES6 also introduces a new kind of parameter, the rest parameters. It also uses the … syntax and come handy if we don’t know how many arguments will be passed in later in the function call. We can use the properties and methods of the Array object on rest parameters:
function sortAlphabets(...args) { let sorted = args.sort(); return sorted; } console.log(sortAlphabets("e","c","a","s","c","r","i","p","t")); // a,c,c,e,i,p,r,s,t
Strings
METHODS
A couple of convenience methods have been added to the String prototype.
'my string'.startsWith('my'); //true 'my string'.endsWith('my'); // false 'my string'.includes('str'); // true
Simple but effective. Another convenience method has been added to create a repeating string:
'my '.repeat(3); // 'my my my '
TEMPLATE LITERAL
ES6 provides us with a new alternative for string concatenation. Template literals allow us to easily create templates in which we can embed different values to any spot we want. To do so we need to use the ${…} syntax everywhere where we want to insert the data that we can pass in from variables, arrays, or objects.
let customer = { title: 'Mr', firstname: 'Paul', surname: 'Davidson', age: '34' }; let template = `Dear ${customer.title} ${customer.firstname} ${customer.surname}! Happy ${customer.age}th birthday!`; console.log(template); // Dear Mr Paul Davidson! Happy 34th birthday!
With template literals, we can easily create multi-line strings using backticks (`) characters:
//ES6 let x = `1... 2... 3 lines long!`; // Works // ES5 equivalents: var x = "1...\n" + "2...\n" + "3 lines long!"; var x = "1...\n2...\n3 lines long!";
Classes
In ES6, classes are declared with the new class keyword, and need to have a constructor() method that is called when a new object is instantiated by using the new myClass() syntax. Unlike function and variable declarations, class declarations are NOT hoisted in ES6.
class Polygon { constructor(height, width) { //class constructor this.name = 'Poly'; this.height = height; this.width = width; } sayName() { //class method console.log('Hi, I am ', this.name + '.'); } } let myPolygon = new Polygon(5, 6); console.log(myPolygon.sayName()); // Hi, I am Poly.
Modules
There were no native modules support in JavaScript. People came up with AMD, RequireJS, CommonJS and other workarounds. But ES6 introduces modules as a native feature.
We need to define each module in its own file, then use the export keyword to export variables and functions to other files, and the import keyword to import them from other files:
// lib/math.js export function sum(x, y) { return x + y; } export var pi = 3.141593; // app.js import { sum, pi } from "lib/math"; console.log('2π = ' + sum(pi, pi));
There can be multiple export statements. Each must explicitly state the type of the exported value (function and var, in this example).
The import statement in this example uses a syntax to explicitly define what is being imported. To import the module as a whole, the * wildcard can be used, combined with the as keyword to give the module a local name:
// app.js import * as math from "lib/math"; console.log('2π = ' + math.sum(math.pi, math.pi));
The import statements are synchronous, but the module code doesn’t execute until all dependencies have loaded.
And many more..
These were just a few useful and quick-to-learn features of ES6. But ECMAScript 6 introduces many more methods. These methods can significantly improve the way we write our scripts.