ES (ECMAScript) is the official name of JavaScript. ES6 was released in June 2015, which is stated as the sixth edition of the language. It is also known as ECMAScript 2015 or ES 2015. This edition includes several new features. Some of the important new features are given below:
- let and const Keywords
- Default Parameters
- Template Literals
- Arrow Functions
- Object Literals
- Destructuring Assignments
- Rest and Spread Operators
- Modules, export and import Keywords
- Classes
1. let and const Keywords:
let and const are two new keywords introduced in ES6 to declare variables. Both have different usage.
let
keyword is similar to var
except it allows declaring variable with block scope. Variables declared with let
inside a block are not accessible from outside code.
var x = 5;
if(some_condition){
let y = 0;
}
console.log(y); // Error: y is not defined
A variable declared with const
is immutable and block scoped. Immutable means the value of the variable cannot be changed or reassigned (variable with constant value). The variable will have block scope similar to let.
let x = 5;
if(some_condition){
const y = 0;
y = 5; // TypeError: Assignment to constant variable.
}
console.log(y); // Error: y is not defined
2. Default Parameters:
With ES6 now we can define function with default or optional value for some argument. It allow named parameters to be initialized with default values if no value or undefined
is passed.
function multiply(num1, num2 = 1) {
return num1 * num2;
}
let result1 = multiply(5); // 5
let result2 = multiply(5, 3); // 15
3. Template Literals:
Template literals are string literals allowing embedded expressions.. It provides an easy way of creating multiline strings and perform string interpolation. The syntax for interpolation is ${}
and ``
is used to create multiline string.
let str1 = "Hello";
let str2 = "World";
let str = `${str1} ${str2}`; // String Interpolation
console.log(str); // Hello World
let multiline = `string text line 1
string text line 2`;
console.log(multiline);
//Output:
"string text line 1
string text line 2"
4. Arrow Functions:
Arrow function is syntactically compact alternative to a regular function expression.
const functionName = (param1, param2, ...) => {
//Body of the function
}
There is no need to use the function
keyword. If the function body contains single line, the functional curly braces {}
and return
statement are also optional.
// Regular Function Expression
var multiply = function(x, y) {
return x * y;
}
// ES6 Arrow Function
const multiply = (x, y) => x * y;
// ES6 Arrow Function with {}
const multiply = (x, y) => {
let result = x * y;
return result;
}
5. Object Literals:
Object literal provides short hand syntax for common Object
property definition. If Object keys resemble local variables name, assigning value to key is optional.
let firstName = 'Jhon',
let lastName = 'Cena';
// ES6 Object Literals Short Syntax
let userName = { firstName, lastName };
console.log(userName);
// Output:
{
firstName: "Jhon",
lastName: "Cena"
};
6. Destructuring Assignment:
The destructuring assignment syntax is a JavaScript expression that makes it possible to extract values from arrays, or properties from objects, into distinct variables.
Array destructuring example:
let name, age;
[name, age] = ["Sam", 35];
console.log(name); // Sam
console.log(age); // 35
Object destructuring example:
const user = {name: "Sam", age: 35, city: "Bengaluru"};
const {name, age, city} = user;
console.log(name); // Sam
console.log(age); // 35
console.log(city); // Bengaluru
7. Rest and Spread Operators:
The rest and spread operators have same syntax – three dots (...)
, but the usage depends on context. The rest operator is used with destructuring assignment and it represents collection of all remaining elements. Let’s try to understand this with array and object destructuring examples:
// Rest Operator With Array Destructuring
let a, b, rest;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest); // [30,40,50]
// Rest Operator With Object Destructuring
let {a, b, ...args} = {a: 10, b: 20, c: 30, d: 40, e: 50}
console.log(a); // 10
console.log(b); // 20
console.log(args); // {c: 30, d: 40, e: 50}
The spread operator allows expansion of iterables such as arrays, objects, and function’s arguments in place where zero or more elements (for array), zero or more key-value pairs (for object literals) and zero or more arguments (for function calls) are expected.
Learn more about spread operator : Spread Operator in JavaScript
8. Modules, export and import Keywords :
Modules are piece of JavaScript code written in a file. Modules help organize related code and enhance code re-usability. A module can have variables and functions. Variables and functions defined within a module should be exported using the keyword export
so that they can be accessed from other files. Other files can use module code by using the keyword import
.
// calculator.js
let add = function(x, y){
return x + y;
}
let multiply = function(x, y){
return x * y;
}
export {add, multiply}
// app.js
import {add, multiply} from './calculator.js';
console.log(add(10, 15)) // 25
Instead of importing each module functions by name, we can also import entire module.
import * as calc from './calculator.js';
console.log(calc.add(10, 15)) // 25
9. Classes:
Another important feature introduced in ES6 is Object Oriented Programming (OOP) Concept class. A class in terms of OOP is a blueprint for creating objects. It is defined using the keyword class
and properties are assigned inside a constructor()
method. The constructor method is called each time an object is initialized.
The Syntax:
class className{
}
Here is an example:
class User{
constructor(name, age) {
this.name = name;
this.age = age;
}
test() {
console.log("User age is :"+ this.age);
}
}
// Create Object
let user1 = new User("Lokesh", 35);
console.log(user1.name); // Lokesh
// Calling member function
console.log(user1.test()); // User age is :35
We can also have static
member functions in a class. We can create a child class by extending parent class using extends
keyword (Inheritance).