Friday, November 22, 2024
Google search engine
HomeLanguagesJavascriptIntroduction to ES6

Introduction to ES6

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 that tells us how to use a scripting language.

ES6

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 the developers’ favorite so in the ES6 version, we were introduced to const and let keywords which allow us to store variables. They both have their own way of storing variables.

const: The const keyword is mainly used to store that variable whose 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 variable
name = 'Rahul';
console.log(name); // Will give TypeError.


Output: In the above code we declared a variable name with the 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 the const keyword.

javascript




// Object using const
const 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, 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 the conclusion that object properties are mutable even when declared with a const keyword. 

let: In the case of the let keyword, the variables declared will be mutable i.e. their values can be changed. It works similarly to the var keyword with some key differences like scoping which makes it a better option when compared to var.

Example:

javascript




// let
let name = 'Mukul';
console.log(name); // Mukul
 
name = 'Rahul';
console.log(name); // Rahul


Output: Objects are mutable too. Like: 

Example:

javascript




// Object using let
let 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 make your code more readable, and more modern. 

javascript




// ES5
function printName(name){
    console.log('Hello '+name);
}
 
printName('Mukul'); // Hello Mukul


Output:

Instead of using this, use the below code: 

javascript




// ES6
const printName = name =>{
    return `Hi ${name}`; // using template literals
}
console.log(printName('Mukul')); // Hi Mukul
 
// We can also write the above code without
// the return statement
const printName1 = name => `Hi ${name}`;
 
console.log(printName1('Mukul')); // Hi Mukul


Output: 

Template literal

Template literals are a feature of ES6 that allows us to work with strings in a better way when compared to ES5 and below. By simply using template literals, we can improve the code readability. Before ES6 we made use of the ‘+’ 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




// ES5
var name = 'Mukul Latiyan';
console.log('My name is '+ name);
 
// ES6
const name1 = 'Mukul Latiyan';
console.log(`My name is ${name1}`);


Output: 
 

Object and Array Desctructuring

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 destructuring

javascript




// ES5
const college = {
    name : 'DTU',
    established : '1941',
    isPrivate : false
};
 
let name = college.name;
let established = college.established;
let isPrivate = college.isPrivate;
 
console.log(name); // DTU
console.log(established); // 1941
console.log(isPrivate); // false


Output: 

The new way to do this using ES6 is: 

javascript




// ES6
const college = {
    name : 'DTU',
    established : '1941',
    isPrivate : false
};
 
let{name,established,isPrivate} = college;
 
console.log(name); // DTU
console.log(established); // 1941
console.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 Destructuring

In case of destruction of arrays we can simply replace the curly brackets with square brackets. 
Like: 

javascript




// ES6
const arr = ['lionel','messi','barcelona'];
 
let[value1,value2,value3] = arr;
 
console.log(value1); // lionel
console.log(value2); // messi
console.log(value3); // barcelona


Output: 

Default Parameters

Default parameters allow you to define a parameter in advance, which can be helpful in certain scenarios. In javascript, the 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 assigning a value if they are undefined. 

javascript




// ES5
function fun(a,b){
    return a+b;
}
 
console.log(fun(2,1)); // 3
console.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)); // 3
console.log(fun(2)); // 3


Output: 


After ES6 we can simply write: 

javascript




// ES6
function fun(a,b=1){
    return a + b;
}
 
console.log(fun(2,1)); // 3
console.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 ES6
class 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-10R
console.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. 

javascript




// simple function
function fun(a,b){
    return a + b;
}
 
console.log(fun(1,2)); // 3
console.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 the case with the rest parameter. 

javascript




// ES6 rest parameter
function fun(...input){
    let sum = 0;
    for(let i of input){
        sum+=i;
    }
    return sum;
}
 
console.log(fun(1,2)); // 3
console.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 the spread operator, as: 

javascript




// Spread operator
let 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 the function parameter, it’s the rest parameter.
  • When … occurs in the function call or like, its called a spread operator.

RELATED ARTICLES

Most Popular

Recent Comments