JavaScript: The New Parts

0
4192

logo_JavaScript

This article is the fourth part in this series. The author discusses the for…of iterator, collections and arrow functions.

The JavaScript language is evolving to enable the development of complex and large applications. This is a multi-year effort by ECMA (a standards body). In the previous article or third part of this series, we learnt about computed property keys and string functions. Their support is available in most recent versions of browsers. In this part, we will learn about a control structure for collections, new collection data structures and abbreviated syntax for function-definition using the arrow symbol (=>). The arrow function is an exciting feature of ES6, loved by most JS enthusiasts.

The for..of iterator
JavaScript has for and for…in control statements to loop through a block of code a number of times and traverse through properties of an object, respectively. Note that for…in loops through the properties of an object. In ES6, a new looping structure for…of is introduced to loop through values of a collection. In addition to strings and arrays, we have Maps and Sets introduced in ES6.

Snippet 1: Example of an existing for..in and new for..of looping statement

1. let arr = [“mon”, “tue”, “wed”];
2. for (let i in arr) {
3. console.log(i); //prints index
4. }
5. for (let i of arr) {
6. console.log(i); //prints values
7. }
8. for (let [i,v] of arr.entries()) {
9. console.log(i, “: “, v); // prints index, values
10.}

Output:

0
1
2
mon
tue
wed
0: mon
1: tue
2: wed

In Lines 2-4, we have the looping structure, which displays only the index in case of arrays and property names in case of objects. In Lines 5-8, the new for..of statement assigns the value of the array to i. Lines 8-10 show another variation, where we have both the index and the value captured.
Snippet 2: String object iterated using for…of loop

1. var str = “ES6”;
2. for (let i of str) {
3. console.log(i);
4. }

Output:

E
S
6

for..of can also be used to iterate through the arguments object of a function/method. Note that arguments is a local variable available within all functions.
Snippet 3: Example to demonstrate arguments object

1. function fn(one, two, three) {
2.for(let arg of arguments) {
console.log(arg);
3.}
4. }
5. fn(“mon”,”tue”,”wed”);
Output:
mon
tue
wed


let makept = (a, b) => ({ x:a, y:b});

Arrow function that returns an object.

let capcat = (a, b) => {
let c = a.toUpperCase() 
c += “ “ + b.toUpperCase();
return c;
}

Arrow function with body and an explicit return at the end.

In addition to strings, arrays, arguments and new collections, for…of can also be useful with DOM manipulation.
To provide this capability of iterating through values, built-in functions have been added to the array object, i.e., the prototype method of string and array objects has the Symbol.iterator method. This new Symbol.iterator introduction, in combination with other new features such as generators, makes this new for…of statement powerful.

Collections
Maps and Sets are two new categories of collections added to ES6. Maps allow the storing of arbitrary values as a collection, and Sets is used for storing a collection of unique elements.
Map is composed of key-value pairs. Language supports built-in operations of set(), get(), has() and delete().
Set has operations of add(), clear() and has() to add elements, delete all elements and check the presence of an element, respectively.
Two other variants of Map and Set are the WeakMap and WeakSet. The Weak variants of collections have a few restrictions. Weak variants cannot be iterable, which means we cannot use the for…of statement. The second limitation is that we can only store objects and not primitive data types.
One reason for introducing WeakMap and WeakSet is automatic garbage collection. In the case of Map and Set, the programmer needs to take responsibility for checking references and clearing the memory.

Arrow functions
A new shorthand notation for anonymous functions is the arrow function. It is represented by the symbol =>. This notation of equal-to instead of a dash (or hyphen) makes it a fat arrow function. This notation has been borrowed from.CoffeeScript, and is extremely useful when defining callback functions. Arrow functions have more than cosmetic features. They overcome some of the side effects of this binding with traditional functions. In addition, they also help JS engines to perform better with something called ‘tail call optimisations’. For details, go to References at the end of the article.
Let’s look at an example of an anonymous function definition like the one below:

1. var std = function std(yr) {
2. return “ECMAScript” + yr;
3. };
4. console.log(std(“2015”));

With the ES6 arrow function, the same can be shortened to:

1. var std = yr => “ECMAScript”+yr;
2. console.log(std(“2015”));

Output:

ECMAScript2015

Points to note in the new syntax are that the keyword function has been replaced by the => symbol, and there are no parentheses around the parameter. Since the method has only one statement (expression), there are no curly brackets to enclose the function body. There is no return statement as the body of the function is an expression.
Given below are a few examples of arrow functions, with varying number of parameters and body of the function.

let x = () => {};

Arrow function with no parameters and no body.

let y = (a, b) => a + b;

Arrow function with parameters in parenthesis and function body is an expression.
One major advantage of using arrow functions is the binding of this. It is well known that in JavaScript, there is the annoyance of the this keyword taking different values based on invocation. In contrast, in arrow functions, this has lexical scoping, which means there is no binding. The value of this is determined by the containing function. This solves many side effects in callback handlers. Developers who have used libraries like jQuery should be more familiar with this issue.
With these advantages, it might seem that arrow functions are clear replacements to regular functions. While this makes sense in most cases, some differences remain.

Comparison with traditional functions
In comparison with traditional functions, arrow functions cannot be used as constructors. The value of this is fixed and cannot be changed. The local object arguments is not associated with the arrow function, but the calling function.
List processing

[1,2,3,4].map(function (x) {
return console.log(x * x);
});

In ES6

[1,2,3,4].map(x => console.log(x*x));

Features support
The features covered this month are supported by the latest version of Chrome, Firefox and Node 4.0 environments. For more granular feature support, refer to Kangax matrix in References.
In the next part in this series, we will cover the set of features related to function parameters. These are: default function parameters, rest parameters and the spread operator.

References
[1] Play around with ES6 features online http://www.es6fiddle.net/
[2] Tail call optimisation through arrow functions httpshttps://https://leanpub.com/understandinges6/read#leanpub-auto-arrow-functions
[3] Kangax support matrix http://kangax.github.io/compat-table/es6/

LEAVE A REPLY

Please enter your comment!
Please enter your name here