Let's Take A Journey Through ES2015

ES2015 is the latest JavaScript standard release by ECMA (European Computer Management Association) in June 2015. Previously, it was named harmony and then it was changed to ES6 (because this is the 6th release). Finally, the committee decided to change its name to ES2015.

In this version, they have implemented many new features which will entirely change the way of coding in JavaScript. Now, we can  perform modular coding using classes. They made changes in function and its parameters declaration, which will help us to write less error-prone code. The keywords like let and const help us to resolve the issues with var.

We will cover each feature of ES15 in two parts. In the first part, I will focus on features related to variable declaration, new collection, and template strings; and in the second part, I will cover modular approach, class, and function.

let

In JavaScript, we use “var” keyword to define a variable for quite a long time. Issue with the “var” keyword is scope. Suppose if we define a variable in an ‘if’ condition, then also, we will be able to access the variable outside ‘if’ condition. This happens because of the hoisted feature in JavaScript. It drags any variable to the top of the function and defines there, so the variable became accessible from any point in the scope of the function. “let” keyword helps us resolve these issues.

Using ‘let’ keyword, we get the below advantages.

  • It works with in
  • It will not have hoisted with, like var.
  • It will not allow another declaration of same variable with in same scope.
  • Instead of “var”, we should use let within for loop to maintain the scope.

Let’s understand this with an example.

In earlier version of JavaScript (ES5), given is the condition inside which I have initialized variable b and c. Finally, we logged the values in the console. In first look, the output on the right hand side in the console looks weird to me because I defined variable b and c inside if condition, but still, they are accessible outside the condition. Then, I figured out that this is happening because of hosting.

Code Snippet 

  1. <script>  
  2.       (function () {  
  3.           var a = 1;  
  4.           if (a === 1) {  
  5.               var b = 2;  
  6.           }  
  7.           else {  
  8.               var c = 6;  
  9.           }  
  10.           console.log(b);  
  11.           console.log(c);  
  12.       }());  
  13.   </script>  

javascript
Now, let’s see how we can resolve this issue with let keyword. In the below code, I have replaced the “var“ keyword with “let” and I get an exception in the console that b is not defined which looks valid to me because b’s scope should be inside if statement. It also helps us in unwanted update or modification of b variable because variable b can be accessible only inside if condition.

Code Snippet 

  1. <script>  
  2.     (function () {  
  3.         let a = 1;  
  4.         if (a === 1) {  
  5.             let b = 2;  
  6.         }  
  7.         else {  
  8.             let c = 6;  
  9.         }  
  10.         console.log(b);  
  11.         console.log(c);  
  12.   
  13.     }());  
  14.   
  15.     </script>  

javascript
With let, it is not allowed to define same variable twice. First, we will look for the same code with var. Then, we will see how let will solve this issue.

Code Snippet 

  1. <script>  
  2.    (function () {  
  3.        var a = 1;  
  4.        var a = 2;  
  5.        console.log(a);  
  6.    }());  
  7.    </script>  

javascript
In the above example, I can define same variable twice. The below variable is overriding the above variable but this may cause a weird behavior. Using let keyword below, we can observe that it resolves this issue and it throws an exception on console, and Visual Studio is showing a red mark in the editor.

  1. <script>  
  2.    (function () {  
  3.        let a = 1;  
  4.        let a = 2;  
  5.        console.log(a);  
  6.    }());  
  7.    </script>  

javascript
const

Prior to ES2015, we didn’t have any way to define constant variables like we have in C# or in any other languages. It is always recommended not to use magical number; this will give poor readability to our code and we have to always guess what the string or number is for. Suppose we use a variable with var and think of it as a constant but we can update the value of a variable anytime in the entire lifetime of an application. In large applications with a large team, it will be difficult task to prevent updating of same variable from any other part of the application. Const keyword will help us to resolve all the above issues.

In the below code, I have created a variable to define the constant with var but we can update a var variable from any part of the application which will not resolve the purpose of using Constants.

Code Snippet 

  1. <script>  
  2.       (function () {  
  3.           var NO_OF_Request = 10;  
  4.           NO_OF_Request = 20;  
  5.   
  6.           console.log(NO_OF_Request);  
  7.       }());  
  8.   </script>  

javascript

This issue can be resolved with const keyword. In the below code, I have replaced the var with const and while modifying the value, an exception is thrown in console. Also, Visual Studio is showing an error. 

  1. <script>  
  2.   (function () {  
  3.       const NO_OF_Request = 10;  
  4.       NO_OF_Request = 20;  
  5.   
  6.       console.log(NO_OF_Request);  
  7.   }());  
  8.   </script>  

javascript

Objects

In ES2015, new features are added for object structuring and destructuring. We will look into each feature with an example.

Object Initialized shorthand

Let’s look at the example below. A function is defined with name prior ES2015 which accepts two parameters - firstname and lastname and returns the object with first name, last name, and fullname properties. Code works as expected and logging properly in console but the code inside looks repetitive because of property name and its values. In ES2015, we can reduce the repetition using the object initialization shorthand. Code works same as previous but now, the repetitive code is removed and the new code looks better readable than the previous one.

Code Snippet 

  1. <script>  
  2.      (function () {  
  3.          //prior ES2015  
  4.          function PriorES2015(firstname, lastname) {  
  5.              return { firstname: firstname, lastname: lastname, fullname: firstname + lastname };  
  6.          }  
  7.          let user = PriorES2015('Van''Diesel');  
  8.          console.log(user.firstname + ',' + user.lastname + ',' + user.fullname);  
  9.   
  10.      }());  
  11.  </script>  

javascript

Code Snippet 

  1. <script>  
  2.         (function () {  
  3.             //In ES2015  
  4.             function InES2015(firstname, lastname) {  
  5.                 return {  firstname, lastname, fullname :firstname + lastname };  
  6.             }  
  7.             let user = InES2015('Van''Diesel');  
  8.             console.log(user.firstname + ',' + user.lastname + ',' + user.fullname);  
  9.   
  10.         }());  
  11.     </script>  

javascript

Template Strings

Template string is a new feature added in ES2015. Using Template string, we can write multi line string with [ ` ] character at start and end of a string. We can also append variable with a special syntax ${<variable>}. Template string make our code more readable.In the below example we have defined two variables firstName and lastName and using template string.

Code Snippet 

  1. <script>  
  2.        (function () {  
  3.            let firstName = 'Van';  
  4.            let lastName = 'Diesel';  
  5.            let fullname = `Full Name : ${firstName} ${lastName}.`;  
  6.            console.log(fullname);  
  7.        }());  
  8.    </script>  

javascript

Object.assign()

This is a new function added in the ES2015. It will help us to copy values of an object from one or more source to a target object. It is very helpful if a scenario where we need to store settings of control or widget. Every widget has some default setting as well as settings provided by users, user can provide a single setting or can provide multiple settings. In JQuery, we have a method which provide same functionality and we use in almost all plugins. Let’s consider an example and understand its functionality.

Suppose, we are working on a widget which has an Init function which will be called with parameters element and settings. Init function will have a set of widget default values, so the settings we passed in parameter will update the default parameter and apply the settings to the element.

As describe above we have an Init function in which we passed document as element and initVisible as false in settings. Inside Init function, settings passed by users should be used and remaining default settings we can achieved this using Object.assign() function and finally applied the settings in the element. Final output shows that initVisible has false values which is from user settings and showInactive has false value from default setting.

Code Snippet 

  1. <script>  
  2.         (function () {  
  3.             function Init(element, settings) {  
  4.                 var defaultSetting = { initVisible: true, showInactive: false }  
  5.   
  6.                 var setting = Object.assign({}, defaultSetting, settings);  
  7.                 ApplySetting(element, setting);  
  8.             }  
  9.             function ApplySetting(element, setting) {  
  10.                 console.log("Init Visible " + setting.initVisible)  
  11.                 console.log("show Inactive " + setting.showInactive)  
  12.             }  
  13.             Init(document, { initVisible: false });  
  14.         }());  
  15.     </script>  

javascript

Maps

Maps are used to store values in a key value pair, this feature is present in most of the languages. Prior to ES215 also we can create maps but its cause issues when we use object as key because it stores keys in the form of string. Let’s take an example and try to understand the issue.

First we will see the issue in ES5. Suppose we have two keys as objects. Then we assign values to map in for both the keys and log the values in console. The output is different what we expect because it stores keys in the form of string and when to convert object in the form of string it gives “[Object, Object]” so when we assign second value it updates the previous value.

Code Snippet 

  1. <script>  
  2.        var key1 = { user: "Sam" };  
  3.        var key2 = { user: "John" };  
  4.   
  5.        var MyMap = {};  
  6.        MyMap[key1] = 51;  
  7.        MyMap[key2] = 54;  
  8.   
  9.        console.log(MyMap[key1]);  
  10.        console.log(MyMap[key2]);  
  11.    </script>  

javascript

In ES2015 we can create Map with the instance of Map. After updating the code with the Map, we can see that above issue is resolved. 

  1. <script>  
  2.         var key1 = { user: "Sam" };  
  3.         var key2 = { user: "John" };  
  4.   
  5.         var MyMap = new Map();  
  6.         MyMap.set(key1, 51);  
  7.         MyMap.set(key2, 54);  
  8.   
  9.         console.log(MyMap.get(key1));  
  10.         console.log(MyMap.get(key2));  
  11.     </script>  

javascript

In the Map, we have a set method to setting keys we have set() method and getting we have get() method. We can also use iterate method to loop through the objects.

Weak Maps

Weak maps are kind of Map where we only used objects as keys. Primitive types such as string, numbers, Booleans, etc. are not allowed. Weak maps are best for the memory management because garbage collector clears the keys and its values if key are nowhere reference from the code. One important fact about weak maps is that it doesn’t allowed iteration. We must use get method to retrieve data from weak Map. Week map has delete and has method to retrieve which will help us to check if key is present and delete a key and its values.

Code Snippet 

  1. <script>  
  2.        var key1 = { user: "Sam" };  
  3.        var key2 = { user: "John" };  
  4.   
  5.        var MyMap = new WeakMap();  
  6.        MyMap.set(key1, 51);  
  7.        MyMap.set(key2, 54);  
  8.   
  9.        console.log("Has : " + MyMap.has(key1));  
  10.        console.log("Delete : " + MyMap.delete(key1));  
  11.        console.log("Has : " + MyMap.has(key1));  
  12.        console.log("Get Key1 : " + MyMap.get(key1));  
  13.        console.log("Get Key2 : " + MyMap.get(key2));  
  14.    </script>  

javascript

Sets

In JavaScript array, we can add duplicate values. Using Sets, we can create unique collection of objects or primitive types. To set a value in set collection, we use add() method. We can iterate Sets collection. In the below example, I am adding to a set collection. I also tried to add JavaScript twice and log each item in the collection and output shows that only unique items are stored in set collection, it ignores the last value (JavaScript).

Code Snippet 

  1. <script>  
  2.     (function () {  
  3.         let list = new Set();  
  4.         list.add('Web Application');  
  5.         list.add('Web API');  
  6.         list.add('Signal R');  
  7.         list.add('Javascript');  
  8.         list.add('Javascript');  
  9.   
  10.         list.forEach(function (item) {  
  11.             console.log(item);  
  12.         })  
  13.     }());  
  14. </script>  

javascript

Weak Sets

Like weak map, weak sets are also memory efficient and we can only use objects with week sets, no primitive types are allowed. Weak sets don’t have any read property or method. It has two methods other than add, "has" and "delete". We can check if a value is present in collection or not and as per that, we can put some logic.

Other than the above features, ES2015 has features like arrow function, class, modules, default parameters etc. which we will cover in next article. 

Reference
  • https://www.codeschool.com/courses/es2015-the-shape-of-javascript-to-come
  • https://themeteorchef.com/blog/what-is-es2015
  • http://www.ecma-international.org/ecma-262/6.0/

Up Next
    Ebook Download
    View all
    Learn
    View all