Arrow functions - AutolabJS/autolabcli GitHub Wiki

TL;DR

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Hence, we use the named functions only where there is an explicit need for function specific this or prototypical this, i.e. for objects, and/or there is a need for function declarartions hoisting. In the project, we use them in the tests, and in eval.js where there is an explicit need for the prototypical this.

So, by default we use the Arrow functions everywhere else.

Introduction

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.

Basic syntax of these functions is:

(param1, param2, …, paramN) => { statements };
(param1, param2, …, paramN) => expression;
singleParam => { statements }

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

Arrow functions fix the this issue which is generally faced when one tries to access an enclosing/object scope's this. The following examples illustrates the same:

function Person() {
  var that = this;
  that.age = 0;

  setInterval(function growUp() {
    // The callback refers to the `that` variable of which
    // the value is the expected object.
    that.age++;
  }, 1000);
}

// With the use of Arrow functions:

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the Person object
  }, 1000);
}

var p = new Person();

As the arrow functions don't support argumnents object, we use rest parameter.

function max() {
  return `${arguments[0]} is ${arguments[1]}`;
}

// is equivalent to

var max = (...args) => `${args[0]} is ${args[1]}`;

Conventions

We use arrow functions almost everywhere, mainly because they provide the following features:

  • Scope safety: When arrow functions are used consistently, everything is guaranteed to use the same this as the global scope. Mixig in with arrow functions with named functions increase the chances of the scopes being messed up.
  • Compactness: Arrow functions are easier to read and write.
  • Clarity: When almost everything is an arrow function, any regular function immediately sticks out for defining the scope. A developer can always look up the next-higher function statement to see what the thisObject is.

Further, we use named functions only when we need object methods, and when declarartions need to be hoisted.