Skip to content
On this page

Arrow Functions

Introduction

ES6 introduced a new type of function: the arrow function.

Why is it called an arrow function? Because its definition uses an arrow:

javascript
x => x * x

The above arrow function is equivalent to:

javascript
function (x) {
    return x * x;
}

Before diving deeper into arrow functions, check if your browser supports ES6's Arrow Function:

javascript
let fn = x => x * x;
console.log('Your browser supports ES6 Arrow Functions!');

Syntax

Arrow functions are similar to anonymous functions and simplify function definitions. There are two formats: one that includes a single expression, omitting { ... } and return, and another that can include multiple statements, requiring { ... } and return:

javascript
x => {
    if (x > 0) {
        return x * x;
    } else {
        return -x * x;
    }
}

If the number of parameters is not one, you need to use parentheses:

javascript
// Two parameters:
(x, y) => x * x + y * y

// No parameters:
() => 3.14

// Variable parameters:
(x, y, ...rest) => {
    let sum = x + y;
    for (let i = 0; i < rest.length; i++) {
        sum += rest[i];
    }
    return sum;
}

To return an object, you need to be cautious; for a single expression, this will cause an error:

javascript
// SyntaxError:
x => { foo: x }

Instead, write it like this:

javascript
// ok:
x => ({ foo: x })

this in Arrow Functions

Arrow functions look like a shorthand for anonymous functions, but there's a key difference: the this in an arrow function is lexically bound, determined by the context.

For example, consider this scenario where this doesn't point as expected:

javascript
let obj = {
    birth: 1990,
    getAge: function () {
        let fn = function () {
            return new Date().getFullYear() - this.birth; // `this` points to window or undefined
        };
        return fn();
    }
};

With arrow functions, this correctly points to the lexical scope, which is the outer object obj:

javascript
let obj = {
    birth: 1990,
    getAge: function () {
        let fn = () => new Date().getFullYear() - this.birth; // `this` points to obj
        return fn();
    }
};
obj.getAge(); // 25

You no longer need the old workaround of assigning this to a variable:

javascript
let that = this;

Since this is lexically bound in arrow functions, using call() or apply() will not bind this:

javascript
let obj = {
    birth: 1990,
    getAge: function (year) {
        let fn = (y) => y - this.birth; // `this.birth` is still 1990
        return fn.call({ birth: 2000 }, year);
    }
};
obj.getAge(2015); // 25

Practice

Simplify the sorting function using an arrow function:

javascript
let arr = [10, 20, 1, 2];
arr.sort((x, y) => x - y);
console.log(arr); // [1, 2, 10, 20]
Arrow Functions has loaded