Modern Javascript: Features of ES6

Modern Javascript: Features of ES6

Hello hashnode family, welcome to this article where I tried to explain the features of ES6. I have elaborated features as I learning them. I will suggest first read the concept one by one and then practice it.

ES6 features:

  1. Variables can be created with two new keywords i.e. let, and const.
  2. Template Literals
  3. Arrow Functions
  4. Rest and spread operator
  5. Destructuring
  6. Array Functions
  7. Classes

1. Variables using let and const keyword

Before going to the variables introduced in ES6, let's understand the scope. There are three types of scope in Javascript.

Block Scope:

Variables declared inside the block can not be accessed from outside the block.

Function Scope:

Variables declared inside a function can be accessed anywhere inside the function.

Global Scope:

Variables declared globally can be accessed anywhere in the javascript program.

let keyword:

A variable can be created using the let keyword. It can be re-assigned with different values within the scope.

Javascript code to demonstrate:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Let Keyword</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>

        let message = "Hello javascript";   //Global Variable
        let ver = 6.0;     //Global Variable 
        console.log(message);    // prints "Hello javascript" on console
        // here it can be re-assigned.
        message = "Hello Modern Javascript";
        console.log(message);    // prints "Hello Modern Javascript" on console
        console.log(ver);        // print 6.0 on console
        {
            let message2 = "It can not be accessed outside the block scope"; // block scope
            // Access a message keyword
            console.log(message);
        }
        console.log(message2);  //ReferenceError: message2 is not defined

</script>
</head>

<body>
</body>

</html>

To know more about let click here..

const keyword:

A variable can be created using the const keyword. Like let, a const variable can not be re-assigned. It will give a type error.

Note: You need to assign a value when you are creating a const variable otherwise program will give a syntax error

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Const Keyword</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>

        const message = "Hello javascript";   //Global Variable
        console.log(message);    // prints "Hello javascript" on console
        // here it can not be re-assigned.
        // message = "Hello Modern Javascript";  // TypeError: invalid assignment to const 'message'

        {
            const message2 = "It can not be accessed outside the block scope"; // block scope
            // Access a message keyword
            console.log(message);
        }
        console.log(message2);  //ReferenceError: message2 is not defined

        // Declaring a varaible withour assignment of value gives an syntax error
        const versionjs;   // missing = in const declaration
        versionjs = 6.0;  
</script>
</head>

<body>
</body>

</html>

To know more about const click here..

2. Template Literals or Template Strings:

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

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.

To escape a backtick in a template literal, put a backslash (\) before the backtick. The below program will demonstrate how template strings are created and used. It is easier to create. As compared to string concatenation, template strings are less complex.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Template String</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        // function which returns a string using string concatenation
        function fullNameRegular(firstName, lastName){
            return 'Hello '+ firstName+' '+lastName+', Happy Birthday To You!';
        }
        // function which returns a string using template string
        function fullName(firstName, lastName){
            return `Hello ${firstName} ${lastName}, Happy Birthday To You!`;
        }
        let firstName = "Hrishikesh";
        let lastName = "Salunkhe";
        // prints "Hello Hrishikesh Salunkhe, Happy Birthday To You!"
        console.log(fullName(firstName, lastName));    // template string function call 
        // prints "Hello Hrishikesh Salunkhe, Happy Birthday To You!"
        console.log(fullNameRegular(firstName, lastName));  // string concatenation function call
    </script>
</head>

<body>
</body>

</html>

3. Arrow Functions

Arrow Function is a way to create traditional function. I demonstrated some ways of creating with different requirements in the below code. You have to practice for a better understanding of the arrow functions.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Arow Function</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        // Regular Function
        function regfunction(name, age) {
            return "Hello " + name + ", you are " + age + " years old!";
        }


        // Arrow Function
        const arrow = (name, age) => {
            return `Hello ${name}, you are ${age} years old!`;
        };


        // Arrow function with single parameter and single expression
        const arrow1 = name => `Hello ${name}, welcome to Modern Javascript`;


        // Arrow function with single parameter and multiple statements
        const arrow2 = age => {
            if(age >= 18){
                return  `Congrats, You are ${age} years old. You can vote, `;              
            }
            else{
                return  `Sorry, You are ${age} years old. You can not vote, `;   
            }
        }


        // Arrow function with no parameter and multiple Statements
        const arrow3 = () => {
            const age =19;
            const name = "Hrishikesh";
            if(age >= 18){
                return  `Congrats ${name}, You are ${age} years old. You can vote, `;              
            }
            else{
                return  `Sorry ${name}, You are ${age} years old. You can not vote, `;   
            }
        }


        // Arrow function with more than one parameters and multiple Statements
        const arrow4 = (name,age) => {
            if(age >= 18){
                return  `Congrats ${name}, You are ${age} years old. You can vote, `;              
            }
            else{
                return  `Sorry ${name}, You are ${age} years old. You can not vote, `;   
            }
        }


        // Arrow function with more than one parameters and single expression
        const arrow5 = (name, age) => {
            return `Hello ${name}, you are ${age} years old!`;
        };
        console.log(regfunction("Hrishikesh", 21));  // prints"Hello Hrishikesh, you are 21 years old!"
        console.log(arrow("Hrishikesh", 21));        // prints "Hello Hrishikesh, you are 21 years old!"
        console.log(arrow1("there"));
        console.log(arrow2(22));
        console.log(arrow3());
        console.log(arrow4("Ananya",25));
        console.log(arrow5(" Modern Javascript", 6));
    </script>
</head>

<body>
</body>

</html>

4. Rest and spread operator:

Rest Operator:

Rest Operator syntax allows a function to accept an indefinite number of arguments as an array.

Note:

  1. A function definition can have only one ...rest_operator
  2. Rest operator must be the last parameter in the function definition
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Rest Operator</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        // We can pass as many as number of parameters to averageSalary function
        function averageSalary(...args){
            const totalMonths = args.length;
            let average;
            let sum = 0;
            for(let i = 0; i < args.length; i++){
                console.log(args[i]);
                sum = sum + args[i];
            }
            average = sum/ totalMonths;
            return average;

        }
        let aveSalary =  averageSalary(20000,22000,22000,22000,26000,50000);
        console.log("The average salary is: ", aveSalary);


        aveSalary =  averageSalary(45000, 48000,50000,80000);
        console.log("The average salary is: ", aveSalary);

        aveSalary =  averageSalary(1000,1222,111,11111,111111,99999,1000,1222,111,11111,111111,99999);
        console.log("The average salary is: ", aveSalary);
    </script>
</head>

<body>
</body>

</html>

Spread Operator:

Spread operator allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Spread Operator is opposite of rest operator. It expands an array or object, unlike the rest operator who is collecting into an array.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Rest Operator</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        function spread(name, age){
            console.log(`Hello ${name}, you are ${age} years old`);
        }
        let myArr = ["Hrishikesh", 21];
        // Spread operator on function calls
        spread(...myArr);

        // Spread operator on Array literals
        let myDetails = [...myArr, 6.1, "Pune"];
        console.log(myDetails);

        // Spread operator on Object literals

        let myObj = {
            name:"Hrishikesh",
            age: 21
        };
        let myDetailsObj = {...myObj};
        console.log(myDetailsObj);


    </script>
</head>

<body>
</body>

</html>

5. Destructuring:

The destructuring syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

 <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Destructuing</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        // Array Destructuring
        const Arr = ["Hrishikesh", "Salunkhe", 22,"Pune, Maharashtra"];
        const [firstName, lastName] = Arr;
        console.log(firstName);
        console.log(lastName);


        // Object Destructuring
        const myDetails ={
            first : "Hrishikesh",
            last : "Salunkhe",
            age : 22,
            address : "Pune. Maharashtra"
        };
        const {first, last, age} = myDetails;
        console.log(first);
        console.log(last);
        console.log(age);
    </script>
</head>

<body>
</body>

</html>

6. Array Functions:

Map Function:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Array Map Function</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        // Array map on array
        const myArray = [1, 2, 3, 4, 5];
        const myArray2 = myArray.map(
            item => item * item);
        console.log(myArray);
        console.log(myArray2);

         // Array map on objects
        const myObject = [{name : "Hrishikesh Salunkhe", age: 22}, 
        {name : "pqr zyx", age: 22},
        {name : "Abc xyz", age: 28} ];
        const myObject2 = myObject.map (item =>
         [name, age] =  [item.name , item.age] );
         console.log(myObject);
         console.log(myObject2);
    </script>
</head>

<body>
</body>

</html>

reduce function:

The reduce() method executes a reducer function on each element of the array, resulting in a single output value.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Array Reduce Function</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        // Array reduce on array
        let total = [1, 2, 3,4,5,6,7,8,9,10].reduce(
            (accumulator, currentValue) => accumulator + currentValue,0);
        console.log(total);

        // Array map on objects
        let initialValue = 0
        let sum = [{ x: 1 }, { x: 2 }, { x: 3 }].reduce(
            (accumulator, currentValue) => accumulator + currentValue.x
            , initialValue);

        console.log(sum);
    </script>
</head>

<body>
</body>

</html>

filter Function:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Array Filter Function</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

        const result = words.filter(word => word.length > 6);

        console.log(result);
    </script>
</head>

<body>
</body>

</html>

find and findIndex function:

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Array find Function</title>
    <meta name="author" content="Hrishikesh Salunkhe">
    <meta name="description" content="Modern javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script>
        const array1 = [5, 12, 8, 130, 44];

        // find function
        const found = array1.find(element => element > 10);
        console.log(found);

        // findIndex function
        const isLargeNumber = (element) => element > 13;
        console.log(array1.findIndex(isLargeNumber));

    </script>
</head>

<body>
</body>

</html>

7. Classes:

Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100

Thank you for your patience to read it.