Skip to main content

Learning ES6 - Arrow functions and the visibility of this and arguments scope in it

Last week I looked at the use of let and const keywords in ES6. This week I have been looking at Arrow function expressions, which enable you to create functions without using the function keyword. They provide a shorter syntax to represent a function. I assumed that arrow functions only provide syntax sugar and all function expressions can be replaced with the new syntax. However, the scopes - this and arguments refers to the enclosing scope and not that of the caller.

Shorter syntax:

Functions with only a return statement can now be represented using a shorter syntax:

[1, 2, 3].map(x => x*x) (() => [1, 4, 9])()

In the first example, the arrow function expression takes only one parameter (x) and returns the square of that parameter. Notice that the expression does not have parentheses and does not use function brackets({}) or the return statement. To represent the expression 'x => x*x' in ES5, you would write:

function (x) { return x*x; }

In the next example, the arrow function expression does not take any parameters and thus you will need to specify empty parentheses followed by the fat arrow (=>)

In a case where more than one parameter is present then it is mandatory to use parentheses:

((x, y) => x + y)(3, 4)

In a case where the return value is represented using the object literal notation then the return value will have to be wrapped in a set of parentheses:

((x, y) => ({x, y}))(1, 2)

Notice that the return object is represented as {x, y} instead of {x: x, y: y}. This is another addition to language; here {x, y} translates to {x: x, y: y}. It is mandatory to specify parentheses because the object literal notation would be considered as start of the function body with the use of '{' and that would result in a syntax error.

Default value for parameters:

Arrow function expressions and functions now allow you to specify default values to the parameters:

((x=1, y=2) => x + y)(10); ((x=1, y=2) => x + y)(undefined, 10);

The default value for the second parameter  - 'y' is 2 and when the function is invoked without specifying the second parameter then the default value is assigned to the parameter. In a case where the value for the first parameter is unknown then one has to specify 'undefined' when invoking the function.

The rest parameter allows you to design functions with variable parameters. Here's the signature of the function:

((x, y, ...rest) => rest.length)(1, 2, 3, 4, 5);

The '...<param_name>' notation is used to capture extra arguments passed to the function. Notice that it's different from the arguments scope; the rest parameter stores the remaining parameters whereas arguments scope would refer to all the parameters passed to the function.

this and arguments scope inside arrow function expression:

Although, it may appear that every function expression can now be replaced with an arrow function expression, be careful when you use this, arguments and super in it. Instead of referring to the caller, scopes - this and arguments would refer to the enclosing function scope.

Consider this example:

var obj = {x: 1}; obj.getObjV1 = function () { console.log(this.x); //prints value of x }; obj.getObjV2 = (() => { console.log(this.x); //this is undefined console.log(arguments); //arguments that the parent function is called with }); obj.getObjV1(); obj.getObjV2();
Using the function expression you would notice that this scope is available. However, inside the body of an arrow function this scope is undefined and thus would result in an error. An arrow function refers to enclosing function's this and arguments scope:

function Foo(x, y) { this.a = 1; setTimeout((x, y) => { console.log(this.a); //referrence to this is available. console.log(arguments); //prints 10, 11 })(5, 6); }; var bar = new Foo(10, 11);

I would use arrow function expressions in callback functions where reference to this scope is to be obtained from it's enclosing function scope. In may scenarios I would have written var self = this; and use self to refer to this scope inside the callback function. This was a hack and now it's no longer required.

Comments

Post a Comment

Popular posts from this blog

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code.

What is Minification?

Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript file…