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

Popular posts from this blog

File upload and Progress events with HTML5 XmlHttpRequest Level 2

The XmlHttpRequest Level 2 specification adds several enhancements to the XmlHttpRequest object. Last week I had blogged about cross-origin-requests and how it is different from Flash\Silverlight's approach .  With Level 2 specification one can upload the file to the server by passing the file object to the send method. In this post I'll try to explore uploading file using XmlHttpRequest 2 in conjunction with the progress events. I'll also provide a description on the new HTML5 tag -  progress which can be updated while the file is being uploaded to the server. And of course, some ColdFusion code that will show how the file is accepted and stored on the server directory.

Server sent events with HTML5 and ColdFusion

There are several ways to interact with the server apart from the traditional request\response and refresh all protocol. They are polling, long polling, Ajax and Websockets ( pusherapp ). Of all these Ajax and Websockets have been very popular. There is another way to interact with the server such that the server can send notifications to the client using Server Sent Events (SSE) . SSE is a part of HTML5 spec:  http://dev.w3.org/html5/eventsource/

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.