ES6 stands for ECMAScript 6, also known as ECMAScript 2015. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009.
Some of My favourite features of ES6 are:
Arrow Function:
Arrow functions allow a shorthand syntax for writing function expressions. You don't need the function keyword, the return keyword, and the curly brackets.
You can only omit the return keyword and the curly brackets if the function is a single statement.
They support both statement block bodies as well as expression bodies which return the value of the expression.
Arrow functions are not hoisted. They must be defined before they are used.
- e.g
const add = (a, b) => { return a + b }; const x = () => x * 4; const y = n => y + n;
Template Literals:
Template literals are string literals allowing embedded expressions.
Template literals are enclosed by the backtick
(``)
character instead of double or single quotes.Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). The expressions in the placeholders and the text between the backticks
(``)
get passed to a function.e.g.
const str = `the sum of a and b is ${a + b}`;
Rest Parameters:
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.
e.g.
function sum(...rest) { return rest.reduce((prev, curr) => { return prev + curr; }); } console.log(sum(1, 2, 3)); // expected output: 6 console.log(sum(1, 2, 3, 4)); // expected output: 10
Spread Operator:
Spread syntax
(...)
allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (e.g. function calls) or elements (e.g. array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (e.g. object literals) are expected.e.g.
function add(x, y, z) { return x + y + z; } const num_list = [1, 2, 3]; console.log(add(...num_list)); // expected output: 6
let and const:
let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.
e.g.
let a = 5; if (a === 5) { let a = 10; console.log(a); // expected output: 10 } console.log(a); // expected output: 5
Constants are block-scoped, similar to the variables declared using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared.
e.g.
const num = 5; try { num = 10; } catch (err) { console.log(err); // expected output: TypeError: invalid assignment to const `num' } console.log(num); // expected output: 5