Javascript - Arrow Function Expression

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

An arrow function expression has a shorter syntax than a function expression and does not bind its own:

  • this,
  • arguments,
  • super,
  • or new.target.

These function expressions are best suited for non-method functions.

As an arrow function does not:

  • bind its own this, it doesn't create then its own this context, this has its original meaning from the enclosing context (even in non strict).
  • bind an arguments object. Arguments are simply a reference to the same name in the enclosing scope.
  • bind to new.target. It cannot be used as constructors and will throw an error when used with new.
Advertising

3 - Syntax

(param1 = defaultValue1, param2,, paramN = defaultValueN) => { statements }
(param1 = defaultValue1, param2,, paramN = defaultValueN) => expression  // equivalent to { return expression; }

where:

The following syntax is also supported:

4 - Example

4.1 - Circle Area

var area = (r) => Math.PI * r ** 2;
var rayon = 3;
console.log(`The area of a circle with the rayon ${rayon} is ${area(rayon)}`);

Advertising

4.2 - Destructuring Assignment

var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;

where:

  • in [a, b] = [1, 2]:
    • a get the value 1
    • b get the value 2
  • in {x: c} = {x: a + b}
    • c get the value a + b thus 3
  • then a + b + c equal:
console.log(f());  // 6

5 - Documentation / Reference

web/javascript/es/arrow.txt · Last modified: 2019/02/16 17:40 by gerardnico