Introduction
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, a new collection, and template strings; and in the second part, I will cover the modular approach, class, and function.
let
In JavaScript, we use “var” keyword to define a variable for quite a long time. The 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 within
- It will not have hoisted with, like var.
- It will not allow another declaration of the same variable within same scope.
- Instead of “var”, we should use let within for loop to maintain the scope.
Let’s understand this with an example
In an earlier version of JavaScript (ES5), given is the condition inside which I have initialized variables 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
- <script>
- (function () {
- var a = 1;
- if (a === 1) {
- var b = 2;
- }
- else {
- var c = 6;
- }
- console.log(b);
- console.log(c);
- }());
- </script>
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
- <script>
- (function () {
- let a = 1;
- if (a === 1) {
- let b = 2;
- }
- else {
- let c = 6;
- }
- console.log(b);
- console.log(c);
-
- }());
-
- </script>
With let, it is not allowed to define the 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
- <script>
- (function () {
- var a = 1;
- var a = 2;
- console.log(a);
- }());
- </script>
In the above example, I can define the same variable twice. The below variable is overriding the above variable but this may cause weird behavior. Using let keyword below, we can observe that it resolves this issue and it throws an exception on the console, and Visual Studio is showing a red mark in the editor.
- <script>
- (function () {
- let a = 1;
- let a = 2;
- console.log(a);
- }());
- </script>
Prior to ES2015, we didn’t have any way to define constant variables as 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 a difficult task to prevent updating of the 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
- <script>
- (function () {
- var NO_OF_Request = 10;
- NO_OF_Request = 20;
-
- console.log(NO_OF_Request);
- }());
- </script>
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.
- <script>
- (function () {
- const NO_OF_Request = 10;
- NO_OF_Request = 20;
-
- console.log(NO_OF_Request);
- }());
- </script>
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 a 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 the 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 the same as previous but now, the repetitive code is removed and the new code looks better readable than the previous one.
Code Snippet
- <script>
- (function () {
-
- function PriorES2015(firstname, lastname) {
- return { firstname: firstname, lastname: lastname, fullname: firstname + lastname };
- }
- let user = PriorES2015('Van', 'Diesel');
- console.log(user.firstname + ',' + user.lastname + ',' + user.fullname);
-
- }());
- </script>
Code Snippet
- <script>
- (function () {
-
- function InES2015(firstname, lastname) {
- return { firstname, lastname, fullname :firstname + lastname };
- }
- let user = InES2015('Van', 'Diesel');
- console.log(user.firstname + ',' + user.lastname + ',' + user.fullname);
-
- }());
- </script>
Template Strings
Template string is a new feature added in ES2015. Using Template string, we can write multi-line string with [ ` ] character at the start and end of a string. We can also append variable with a special syntax ${<variable>}. Template string makes our code more readable. In the below example we have defined two variables firstName and lastName and using template string.
Code Snippet
- <script>
- (function () {
- let firstName = 'Van';
- let lastName = 'Diesel';
- let fullname = `Full Name : ${firstName} ${lastName}.`;
- console.log(fullname);
- }());
- </script>
Object.assign()
This is a new function added in the ES2015. It will help us to copy the values of an object from one or more sources 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 provides the same functionality and we use it in almost all plugins. Let’s consider an example and understand its functionality.
Suppose, we are working on a widget that 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 described 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 achieve this using Object.assign() function and finally applied the settings in the element. The final output shows that initVisible has false values which are from user settings and show inactive has a false value from a default setting.
Code Snippet
- <script>
- (function () {
- function Init(element, settings) {
- var defaultSetting = { initVisible: true, showInactive: false }
-
- var setting = Object.assign({}, defaultSetting, settings);
- ApplySetting(element, setting);
- }
- function ApplySetting(element, setting) {
- console.log("Init Visible " + setting.initVisible)
- console.log("show Inactive " + setting.showInactive)
- }
- Init(document, { initVisible: false });
- }());
- </script>
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 causes issues when we use an object as a 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 from what we expect because it stores keys in the form of a string and when to convert objects in the form of string it gives “[Object, Object]” so when we assign second value it updates the previous value.
Code Snippet
- <script>
- var key1 = { user: "Sam" };
- var key2 = { user: "John" };
-
- var MyMap = {};
- MyMap[key1] = 51;
- MyMap[key2] = 54;
-
- console.log(MyMap[key1]);
- console.log(MyMap[key2]);
- </script>
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.
- <script>
- var key1 = { user: "Sam" };
- var key2 = { user: "John" };
-
- var MyMap = new Map();
- MyMap.set(key1, 51);
- MyMap.set(key2, 54);
-
- console.log(MyMap.get(key1));
- console.log(MyMap.get(key2));
- </script>
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 the iterate method to loop through the objects.
Weak Maps
Weak maps are a 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 a key is nowhere reference from the code. One important fact about weak maps is that it doesn’t allow iteration. We must use get method to retrieve data from weak Maps. Week map has delete and has a method to retrieve which will help us to check if key is present and delete a key and its values.
Code Snippet
- <script>
- var key1 = { user: "Sam" };
- var key2 = { user: "John" };
-
- var MyMap = new WeakMap();
- MyMap.set(key1, 51);
- MyMap.set(key2, 54);
-
- console.log("Has : " + MyMap.has(key1));
- console.log("Delete : " + MyMap.delete(key1));
- console.log("Has : " + MyMap.has(key1));
- console.log("Get Key1 : " + MyMap.get(key1));
- console.log("Get Key2 : " + MyMap.get(key2));
- </script>
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 a set collection, it ignores the last value (JavaScript).
Code Snippet
- <script>
- (function () {
- let list = new Set();
- list.add('Web Application');
- list.add('Web API');
- list.add('Signal R');
- list.add('Javascript');
- list.add('Javascript');
-
- list.forEach(function (item) {
- console.log(item);
- })
- }());
- </script>
Weak Sets
Like a 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 real 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 the 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/