[JavaScript – ES2015] Arrow Functions

In short, the arrow is a shorthand of a function using the “=>” syntax. But there is more. How “this” means is really confusing in JavaScript but in an arrow function, “this” is always the surrounding code. This has a huge benefit as you can see shortly.

1. Syntax

The arrow sign “=>” is used to create a function. The left side is the parameters and the right side is the body.

The syntax is very short and expressive.

  • For a single parameter, () can be omitted.
  • If the body has a single statement, the code block { } can be omitted.
  • If the body returns a value from a single expression, even the “return” keyword can be omitted.
let getZero = () => 0;
let increment = x => x + 1;
let print = x => console.log(x);
let add = (x, y) => x + y;
let divide = (x, y) => {
  if (y !== 0) {
    return x / y;
  }
  return 0;
};

  console.log(getZero()); // 0
  console.log(increment(1)); // 2
  print(3); // 3
  console.log(add(2, 3)); // 5
  console.log(divide(10, 5)); // 2

 

2. Anonymous Functions

JavaScript functions can be passed as arguments of other functions. Event handlers and callbacks are a good example. Arrow functions can be very useful to create delegate functions.

[1, 2, 3, 4, 5].forEach(n => {
  console.log(n);
});

 

3. Lexical this

The “this” object is one of the most confusing part of JavaScript. Look at the following class.

class Adder {
  constructor() {
    this._sum = 0;
  }

  get sum() {
    return this._sum;
  }

  add(nums) {
    nums.forEach(function (n) {
      this._sum += n;
    });
  }
}

let adder = new Adder();
adder.add([1, 2, 3]);
console.log(adder.sum); // expects 6

You might expect the result 6. But you will get an error instead.

SCRIPT5007: Unable to get property ‘_sum’ of undefined or null reference

What’s going on here? In a function, “this” can mean the global object in a non strict mode (I think this is a design error), or the execution context object in a strict mode. To provide the context object, you need to execute the function using the “call()” or “apply()“. In the above example, “this” is undefined because we did not provide the context object.

Here are the solutions

  • Old technique to solve this problem is to use closure. Save “this” object to another variable such as “that“.
  • ES5 introduced the “bind()” method to set the value of a function’s “this” regardless of how it is called.
  • ES2015’s arrow function retains the “this” value of the enclosing lexical context, which is called “lexical binding“.

 

class Adder {
  constructor() {
    this._sum = 0;
  }

  get sum() {
    return this._sum;
  }

  add(nums) {
    nums.forEach(n => this._sum += n);
  }
}

let adder = new Adder();
adder.add([1, 2, 3]);
console.log(adder.sum); // 6

You will get 6 as expected without errors.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s