I hope my previous article was clear to give you a basic understanding of ECMAScript 6 and it’s few features. Some features of ES 2015/6 is still relatively new.Now, I am going to explain some more few features of ECMAScript 6 in this article.
Classes and Objects
Here, let’s see the implementation of classes and objects in JavaScript ES6. JavaScript is not a class-based language. Almost, all other languages support classes, developers craving that feature in JavaScript.
Before Es6, Developer was writing classes like this
1 2 3 4 5 6 7 8 9 10 11 | this.greeting = 'Welcome, ' + username; return this.greeting; } var mygreetings = new greetings('Bhumi'); console.log(mygreetings.greeting); |
Now, let’s see the object-oriented programming in JavaScript ES6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | class Greetings{ this.username = "Bhumi"; this.msg = ''; } getGreetings(username){ var user = (typeof username == 'undefined') ? this.username : username; let d = new Date(); let hrs = d.getHours(); if (hrs >= 6 && hrs < 12){ this.msg = "Good morning"; // After 6am }else if (hrs >= 12 && hrs < 17){ this.msg = "Good afternoon"; // After 12pm }else if (hrs >= 17 && hrs < 22){ this.msg = "Good evening"; // After 5pm }else if (hrs > 22){ this.msg = "Go to bed!"; // After 10pm } return `${this.msg} ${user}`; } } const greetingmsg = mygreetings.getGreetings('TheCreativeDev'); const greetingmsg2 = mygreetings.getGreetings();// Good afternoon Bhumi console.log(greetingmsg); console.log(greetingmsg2); |
Above example shows the class declaration, object, and functions. Inside the class, added properties and methods. You don’t need to declare variable directly into the class as ES5, you can use a constructor with this for default declarations. Constructor works same like other languages and when class initiated, this method will run.
Template Literals
Before ES 6, Most annoying part in Javascript was writing out the string with a variable. You can do it by separating each piece of string and variables with plus sign and single quotes which is very tedious.
1 2 3 4 5 6 | const name = 'Bhumi'; const site = 'TheCreativeDev'; console.log('This is ' + name + ' and website is ' + site); |
With ES 6, you can use the template literals which makes code cleaner. With template literals, you just define the string with a set of backtick and wherever you want to insert a variable, you put the dollar sign with the set of curly braces. In between curly braces, you can write the variable name.
1 2 3 | console.log(`This is ${name} and website is ${site}`); |
Template literal makes easier to work with variable and string.
Multi-line string
Multiline string feature is the way reduce your headache of writing multi line HTML.You don’t have to add \n and plus symbol to write multi line string. Here is the example of ES5 in which you need to add + to separate it to new line.
1 2 3 4 5 6 7 8 9 10 11 | var template = '<div class="row">\n' + ' <div class="col-sm-12">\n' + ' <label>Name </label>\n' + ' <input class="form-input" type="text" name="name">\n' + ' <button class="btn-default"></button>\n' + ' </div>\n' + '</div>'; console.log( template ); |
In ECMAScript 6, you can just use the backtick operator so you don’t need to add \n and plus operator. You can add any HTML simply.
1 2 3 4 5 6 7 8 9 10 11 | var template = `<div class="row"> <div class="col-sm-12"> <label>Name </label> <input class="form-input" type="text" name="name"> <button class="btn-default"></button> </div> </div>`; console.log( template ); |
Both codes written above will give you the exact same result. Isn’t it easy?
Spread Operators
Spread Operators in ECMAScripts 6 allows you to easily put the values of the array to another array or object or parameters of the function.
1 2 3 4 5 6 | let arr = ['a', 'b', 'c']; let spread = [1, 2, 3, arr, '4']; console.log(spread); // [1, 2, 3, Array(3), "4"] // Array(3) contains ["a", "b", "c"] |
I have two arrays here and I am passing values of one array into the second array and if you see the output of it, you will see it will have a nested array. So, you can loop through an array and flatten it or loop and push it to another array and create a list of single array.
But ES6 comes with the easiest way and to do is just use spread operator and for that you just need to pass … before the array variable.
1 2 3 4 5 6 | let arr = ['a', 'b', 'c']; let spread = [1, 2, 3, ...arr, '4']; console.log(spread); // [1, 2, 3, "a", "b", "c", "4"] |
So, this spread operator will give me the all values of an array together.
Destructuring Assignment
Destructuring assignments in ECMAScript 6 allows you to assign array and object properties to various variables using syntax like array or object literals. This assignment syntax is extremely concise and at the same time clearer than traditional property access methods.
In general, you are likely to access the first three elements of an array like this:
1 2 3 4 5 | var first = myArray[0]; var second = myArray[1]; var third = myArray[2]; |
If you use deconstructed assignment features, the equivalent code will be more concise and more readable:
1 2 3 | var [first, second, third] = myArray; |
Destructuring of arrays
The above is a simple example of an array destructuring assignment. The general form of its syntax is:
1 2 3 | [ variable1, variable2, ..., variableN ] = array; |
This assigns the value of the corresponding element item in the array to the variable from variable1 to variableN. If you want to declare variables can be added at the same time assigned before the assignment var, let or const keywords, such as:
1 2 3 4 5 | var [ variable1, variable2, ..., variableN ] = array; let [ variable1, variable2, ..., variableN ] = array; const [ variable1, variable2, ..., variableN ] = array; |
To describe destructuring assignment using variable is not appropriate because you can destructure nested array:
1 2 3 4 5 6 | var [a, [[b], c]] = [1, [[2], 3]]; console.log(a); // 1 console.log(b); // 2 console.log(c); // 3 |
Also, you can leave blanks to skip over certain elements in the destructured array:
1 2 3 4 | var [, , c] = [1, 2, 3]; console.log(c); // 3 |
You can also capture all the trailing elements in an array through the indefinite parameters mode:
1 2 3 4 | var [a, ...c] = [1, 2, 3]; console.log(c); // [2, 3] |
Object destructuring
By destructuring the object, you can bind each of its properties to different variables, first specifying the bound property, and then immediately following a variable to be destructured.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | let name = { firstname: "Bhumi", lastname: "Shah" } //ES5 let first = name.firstname; let last = name.lastname; console.log(first); // "Bhumi" console.log(last); // "Shah" //ES6 var { firstname, lastname } = name; console.log(firstname); // "Bhumi" console.log(lastname); // "Shah" |
Here is a very simple example of object called name, and normally if I wanted to access the property, I assign it to the variable and use it. But using destructuring, you can write cleaner code by wrapping variable it into curly braces and you can also add multiple comma separated variables. You can get the exact same result. This only works if the variable you are declaring has the same name as the property you are accessing.
There is a lot more you can do with destructuring.
‘for…of’ loop
How do you loop through the elements in an array in JavaScript? You can implement array traversal using for loop like below example.
1 2 3 4 5 6 7 8 | // for var array = [ 'a' , 'b' , 'c' , 'd' ]; for (var i = 0 ; i < array.length ; i++) { var element = array [ i ]; console.log ( element ); } |
In the official release of ES5,they have added thein-built forEach method to iterate over the array:
1 2 3 4 5 6 | // forEach array . forEach ( function ( element ) { console.log ( element ); }); |
In ECMAScript 6, you can iterate through an array using for…of very easily.
1 2 3 4 5 6 7 8 | //ES 6 // for ...of const myarray = [ 'a' , 'b' , 'c' , 'd' ]; for (const element of myarray) { console.log ( element ); } |
Above piece of code looks more concise, but this method also has a minor drawback. You cannot use the break statement to break the loop and you cannot use the return statement to return to the outer function.
I am going to end this article here. I will write about more features later. If you want to learn more about the ECMAScript 6 or if you have questions about its features, comment in below section.