Introduction to ES6

14 Sep, 2021
ES6 or ECMAScript 2015 is the 6th version of the ECMAScript programming language. ECMAScript is the standardization of Javascript which was released in 2015, and subsequently renamed as ECMAScript 2015.ECMAScript and Javascript are both different in nature. 
ECMAScript vs Javascript
 
ECMAScript: It is the specification defined in ECMA-262 for creating a general purpose scripting language.In simple terms it is a standardization for creating a scripting language.It was introduced by Ecma International, and is basically an implementation with which we learn how to create a scripting language.  Javascript: A general purpose scripting language that conforms to the ECMAScript specification.It is basically an implementation which tells us how to use a scripting language.
ES6
Javascript ES6 has been around for a few years now, and it allows us to write code in a clever way which basically makes the code more modern and more readable. It’s fair to say that with the use of ES6 features we write less and do more, hence the term ‘write less, do more’ definitely suits ES6. ES6 introduced several key features like const, let, arrow functions, template literals, default parameters, and a lot more. Let’s take a look at them one by one.“const” and “let” Before ES6 we mainly made use of the var keyword whenever we wanted to declare a variable. But it had some serious issues, also it was not developers’ favorite so in the ES6 version, we were introduced to const and let keywords which allows us to store variables. They both have their own way of storing variables. 
const: The const keyword is mainly used to store that variable who’s value is not going to be changed.Consider an example where you are creating a web application where you want to store a variable whose value is not going to change, then const is definitely the best choice to store that variable. In javascript, const is considered to be more powerful than var.Once used to store a variable it can’t be reassigned.In simple words, it is an immutable variable except when used with objects.Example:
javascript
// Const const name = 'Mukul';console.log(name); // Will print 'Mukul' to the console.  // Trying to reassign a const variablename = 'Rahul';console.log(name); // Will give TypeError.
Output:In the above code we declared a variable name with const keyword and then console.log it which works fine, but reassigning it with some other value will give an error.Now let’s look at an example where we declare an object using const keyword. 
javascript
// Object using constconst person ={    name:'Mukul Latiyan',    age:'21',    isPlaced:true};  console.log(person.name); // 'Mukul Latiyan'person.name = 'Mayank';  console.log(person.name); //'Mayank'
Output:The properties of the objects declared using the const keywords are mutable, like in the code above we declared a person object with some properties like name, age, isPlaced. When we tried to access the properties all works fine, also when we change the name property it works fine too. Hence we reach to a conclusion that object properties are mutable even when declared with const keyword. let: In case of let keyword, the variables declared will be mutable i.e there values can be changed. It works similar to the var keyword with some key differences like scoping which makes it a better option as when compared to var.
javascript
// letlet name = 'Mukul';console.log(name); // Mukul  name = 'Rahul';console.log(name); // Rahul
Output:Objects are mutable too. Like: 
javascript
// Object using letlet bike = {    name : 'Ninja ZX-10R',    engine:'998cc',    abs : 'dual channel'};  console.log(bike.engine); // 998cc  bike.engine = '789cc';console.log(bike.engine); // 789cc
Output:  
Arrow functions
Arrow functions(also known as ‘fat arrow functions’) are a more concise syntax for writing function expressions.Introduced in ES6, arrow functions are definitely one of the most impactful changes in javascript. These function expressions makes your code more readable, more modern.  
javascript
// ES5function printName(name){    console.log('Hello '+name);}  printName('Mukul'); // Hello Mukul
Output:
Instead of using this, use the below code:  
javascript
// ES6const printName = name =>{    return `Hi ${name}`; // using template literals}console.log(printName('Mukul')); // Hi Mukul  // We can also write the above code without // the return statementconst printName1 = name => `Hi ${name}`;  console.log(printName1('Mukul')); // Hi Mukul
Output:  
Template literal
Template literals are a feature of ES6 which allows us to work with strings in a better way as when compared to ES5 and below. By simply using template literals, we can improve the code readability. Before ES6 we made use of ‘+’ operator whenever we wanted to concatenate strings and also when we wanted to use a variable inside a string which is definitely not a recommended method. Template literals use back-ticks(“) rather than the single or double quotes we’ve used with regular strings.
javascript
// ES5var name = 'Mukul Latiyan';console.log('My name is '+ name);   // ES6const name1 = 'Mukul Latiyan';console.log(`My name is ${name1}`); 
Output:  
Object and Array Destructing
Destructing in javascript basically means the breaking down of a complex structure(Objects or arrays) into simpler parts.With the destructing assignment, we can ‘unpack’ array objects into a bunch of variables. 
Object destruction
javascript
// ES5const college = {    name : 'DTU',    established : '1941',    isPrivate : false};  let name = college.name;let established = college.established;let isPrivate = college.isPrivate;  console.log(name); // DTUconsole.log(established); // 1941console.log(isPrivate); // false
Output:  
The new way to do this using ES6 is:  
javascript
// ES6const college = {    name : 'DTU',    established : '1941',    isPrivate : false};  let{name,established,isPrivate} = college;  console.log(name); // DTUconsole.log(established); // 1941console.log(isPrivate); // false
Output:  
So instead of declaring variables separately for each property of an object we just put our values within curly brackets to get any property of the object. 
Array destruction
In case of destruction of arrays we can simply replace the curly brackets with square brackets. Like:  
javascript
// ES6const arr = ['lionel','messi','barcelona'];  let[value1,value2,value3] = arr;  console.log(value1); // lionelconsole.log(value2); // messiconsole.log(value3); // barcelona
Output:  
Default Parameters
Default parameters allows you to define a parameter in advance, which can be helpful in certain scenarios. In javascript, function parameter default to undefined.However it is useful to set a different default value.Before ES6 the way we used to define default parameters is by testing parameters value in the default function body and assign a value if they are undefined.  
javascript
// ES5function fun(a,b){    return a+b;}  console.log(fun(2,1)); // 3console.log(fun(2)); // 2 + undefined is NaN(not-a-number)
Output:  
We removed this default parameter error like this:  
javascript
// ES5(improved)function fun(a,b){    b = (typeof b!=='undefined')?b:1;    return a + b;}  console.log(fun(2,1)); // 3console.log(fun(2)); // 3
Output:  
After ES6 we can simply write:  
javascript
// ES6function fun(a,b=1){    return a + b;}  console.log(fun(2,1)); // 3console.log(fun(2)); // 3
Output:  
Classes
Classes are the core of Object-Oriented programming(OOPs). ES6 introduced classes in javascript. Classes in javascript can be used to create new Objects with the help of a constructor, each class can only have one constructor inside it.  
javascript
// classes in ES6class Vehicle{    constructor(name,engine){        this.name = name;        this.engine = engine;    }}  const bike1 = new Vehicle('Ninja ZX-10R','998cc');const bike2 = new Vehicle('Duke','390cc');  console.log(bike1.name); // Ninja ZX-10Rconsole.log(bike2.name); // Duke
Output:
Rest parameter and spread operator
Rest Parameter: The rest parameter syntax allows us to represent an indefinite number of arguments as an array.With the help of a rest parameter a function can be called with any number of arguments, no matter how it was defined.  javascriptjavascript// simple functionfunction fun(a,b){    return a + b;}  console.log(fun(1,2)); // 3console.log(fun(1,2,3,4,5)); // 3 Output:In the above code, no error will be thrown even when we are passing arguments more than the parameters, but only the first two arguments will be evaluated. It’s different in case with rest parameter.javascriptjavascript// ES6 rest parameterfunction fun(...input){    let sum = 0;    for(let i of input){        sum+=i;    }    return sum;}  console.log(fun(1,2)); // 3console.log(fun(1,2,3)); // 6 console.log(fun(1,2,3,4,5)); // 15Output:Spread Operator: The Spread operator is another operator provided by ES6 that allows us the privilege to obtain a list of parameters from an array. Consider an example where we have a list of numbers and we return the minimum number from that list.Something like:javascriptjavascriptconsole.log(Math.min(1,2,3,-1)); // -1 Output:Now consider that we have an array instead of a list, this above Math object method won’t work and will return NaN, like: javascriptjavascript// Without spread let arr = [1,2,3,-1];  console.log(Math.min(arr)); // NaNOutput:When ...arr is used in the function call, it “expands” an iterable object arr into the list of arguments.In order to avoid this NaN output, we can use spread operator, as:  javascriptjavascript// Spread operatorlet arr = [1,2,3,-1];  console.log(Math.min(...arr)); // -1Output:Both the spread and the rest operator make use of triple dots (...), and sometimes it’s hard to differentiate which one is rest or spread. Simply remember that:When ... is at the end of function parameter, it’s rest parameter.
javascript
// simple functionfunction fun(a,b){    return a + b;}  console.log(fun(1,2)); // 3console.log(fun(1,2,3,4,5)); // 3 
Output:In the above code, no error will be thrown even when we are passing arguments more than the parameters, but only the first two arguments will be evaluated. It’s different in case with rest parameter.
javascript
// ES6 rest parameterfunction fun(...input){    let sum = 0;    for(let i of input){        sum+=i;    }    return sum;}  console.log(fun(1,2)); // 3console.log(fun(1,2,3)); // 6 console.log(fun(1,2,3,4,5)); // 15
Output:Spread Operator: The Spread operator is another operator provided by ES6 that allows us the privilege to obtain a list of parameters from an array. Consider an example where we have a list of numbers and we return the minimum number from that list.Something like:
javascript
console.log(Math.min(1,2,3,-1)); // -1 
Output:Now consider that we have an array instead of a list, this above Math object method won’t work and will return NaN, like: 
javascript
// Without spread let arr = [1,2,3,-1];  console.log(Math.min(arr)); // NaN
Output:When ...arr is used in the function call, it “expands” an iterable object arr into the list of arguments.In order to avoid this NaN output, we can use spread operator, as:  
javascript
// Spread operatorlet arr = [1,2,3,-1];  console.log(Math.min(...arr)); // -1
Output:
Both the spread and the rest operator make use of triple dots (...), and sometimes it’s hard to differentiate which one is rest or spread. Simply remember that:
When ... is at the end of function parameter, it’s rest parameter.
When ... occurs in function call or alike, its called a spread operator.My Personal Notes
arrow_drop_upSave
sagar0719kumar
Articles
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Group Communication in distributed Systems
Difference Between one-dimensional and two-dimensional array
How compare() method works in Java
Data Conversion in C++
Time complexities of different data structures
Node.js | fs.writeFileSync() Method
Hide or show elements in HTML using display property
Set the value of an input field in JavaScript
How do you run JavaScript script through the Terminal?
Multidimensional array in JavaScript