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

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.

A cheat sheet of keyboard shortcuts in ColdFusion Builder

In my last post I have explained about keyboard shortcuts in ColdFusion Builder 2.0. This blog post contains a list of all shortcut keys and I have listed these keyboard shortcuts based on the categories that it falls into. Well, this post was not planned since users can easily get to know the keyboard shortcuts by navigating to the preferences (ColdFusion -> Profiles -> Keys). However, I met Joshua at Scotch on the rocks in Edinburgh and he suggested that it would be nice to have the list of keyboard shortcuts handy. So this post is for those who would like to have the list with them and refer it whenever required.


Keyboard shortcuts for inserting text:

These are the keyboard shortcuts which are used to insert some text into the editor:

CommandKeyboard shortcuts on WindowsKeyboard shortcuts on MacInsert anchor tagCTRL + T, LCMD + T, LInsert bold tagCTRL + T, BCMD + T, BInsert br tagCTRL + T, RCMD + T, RInsert cfabortCTRL + T, ACMD + T, AInsert cfdumpCTRL + T, DCMD + T, DInsert cfs…