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 bascially an implementation which tells us how to use a scripting language.

ES6

Javascript ES6 has been around for 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 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 to 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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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.

    chevron_right

    
    

    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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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'

    chevron_right

    
    

    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.


    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output:

    Objects are mutable too. Like:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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

    chevron_right

    
    

    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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Instead of using this, use the below code:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

Template literal

Template literals is 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 to with regular strings.


filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

The new way to do this using ES6 is:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

So instead of declaring variables separately for each properties 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)

chevron_right


Output:

We removed this default parameter error like this:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

After ES6 we can simply write:

filter_none

edit
close

play_arrow

link
brightness_4
code

// ES6
function fun(a,b=1){
    return a + b;
}
  
console.log(fun(2,1)); // 3
console.log(fun(2)); // 3

chevron_right


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 constructor, each class can only have one constructor inside it.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // simple function
    function fun(a,b){
        return a + b;
    }
      
    console.log(fun(1,2)); // 3
    console.log(fun(1,2,3,4,5)); // 3 

    chevron_right

    
    

    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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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

    chevron_right

    
    

    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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    console.log(Math.min(1,2,3,-1)); // -1 

    chevron_right

    
    

    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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Without spread 
    let arr = [1,2,3,-1];
      
    console.log(Math.min(arr)); // NaN

    chevron_right

    
    

    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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Spread operator
    let arr = [1,2,3,-1];
      
    console.log(Math.min(...arr)); // -1

    chevron_right

    
    

    Output:

Both the spread and the rest operator makes 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_up

Executive Software Developer at Cavisson Systems

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.