Arrow functions in JavaScript

·

4 min read

Arrow functions in JavaScript

JavaScript Arrow Function

The arrow function is one of the features introduced in the ES6 version of JavaScript. It helps us to write simple, cleaner, and compact versions of regular JavaScript functions. But it is limited and can’t be used in all situations.

Regular function ES5

function newUser(name) {
    return "Hello " + name;
}

Arrow function ES6

const newUser = name => "Hello " + name;

Arrow Function Syntax

For single argument and expression

const functionName = argument => expression;

For multiple arguments and expressions

const functionName = (arg1, arg2, ...arg3) => {
    statement(s);
};

Multiple parameters require parentheses () and Multiline statements require body braces {} and return

Example 1: Arrow function with no arguments

If the function doesn't take any arguments then we should be putting empty parentheses ().

const newUser = () => console.log("Welcome!");
newUser(); // Welcome!

Example 2: Arrow function with one argument

If the function takes only one argument then we can omit the parentheses ().

const newUser = name => console.log("Hello " + name);
newUser("Dev"); // Hello Dev

Example 3: Arrow function with multiple arguments

If the function takes multiple arguments then we should be putting them inside parentheses ().

const newUser = (name, birthday) => console.log("Hello " + name + ". It's your birthday: " + birthday);
newUser("Dev", 1996); // Hello Dev. It's your birthday: 1996

Example 4: Arrow function with one statement

If the function body has only one statement then we can omit curly braces {} and return the keyword.

const newUser = () => console.log("Welcome!");
newUser(); // Welcome!

Example 5: Arrow function with multiple statements

If the function body has multiple statements then we need to put them inside of curly braces {}.

const newUser = (name) => {
    let greeting = "Hello " + name;
    console.log(greeting);
}
newUser("Dev"); // Hello Dev

this with arrow functions

Handling of the this keyword is different in arrow functions compared to regular functions.

With regular function

Inside of regular functions, the this keyword refers to the function where it is called. So this keyword in a regular function represents the object that calls the function.

function User() {
    this.name = 'Moz',
    this.age = 22,
    this.sayAge = function () {

        // this is accessible
        console.log(this.age); // 22

        function innerFunc() {

            // this refers to the global object
            console.log(this.age); // undefined
            console.log(this); // Window {}
        }
        innerFunc();

    }
}

let newUser = new User();
newUser.sayAge();

Output

22
undefined
Window {}

With arrow function

However, there is no binding of this with arrow functions. So with arrow functions, the this keyword always refers to the object that defined the arrow function

function User() {
    this.name = 'Moz',
    this.age = 22,
    this.sayAge = function () {

        console.log(this.age); // 22

        let innerFunc = () => {
            console.log(this.age); // 22
            console.log(this); // User { name: 'Moz', age: 22, sayAge: [Function] }
        }

        innerFunc();

    }
}

let newUser = new User();
newUser.sayAge();

Output

22
22
User { name: 'Moz', age: 22, sayAge: [Function] }

Arguments Binding

Regular functions have arguments binding which means when you pass arguments to a regular function, you can access them using the arguments keyword. For example,

function numbers(){
    console.log(arguments)
}
numbers(2, 4, 6); // [Arguments] { '0': 2, '1': 4, '2': 6 }

However, arrow functions do not have their arguments object. It will throw an error when we try to access it. In short, Arrow functions do not have arguments binding. For example,

let numbers = () => {
    console.log(arguments)
}
numbers(2, 4, 6);
// ReferenceError: Can't find variable: arguments

In most cases, using spread is a good alternative to using an arguments object.

let numbers = (...n) => {
    console.log(n)
}
numbers(2, 4, 6); // [ 2, 4, 6 ]

Things to avoid with arrow functions

1. You should not use arrow functions to create methods inside objects

let User = {
    name : 'Moz',
    age : 22,
    sayAge : () => {
        // 'this' refers to the global
        console.log(this.age);
    }
}
User.sayAge(); // undefined

2. You cannot use the arrow function as a constructor

let User = () => {};
let newUser = new User(); // TypeError: User is not a constructor

3. Arrow functions don't have access to the new.target keyword.

4. Arrow functions aren't suitable for the call, apply, and bind methods, which generally rely on establishing a scope.


Wrapping up!

Sometimes the behavior of regular functions is what you want, if not, use arrow functions. Also, Arrow functions were introduced in ES6. Some browsers may not support the use of arrow functions.

That's all for this article, hope you learned something. Thanks for reading, catch you later.

You can also buy me a coffee that would help me grow as a frontend developer :)

Buy Me A Coffee