DEV Community

Cover image for Arrow functions in JavaScript
Moazam Ali
Moazam Ali

Posted on

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;
}
Enter fullscreen mode Exit fullscreen mode

Arrow function ES6

const newUser = name => "Hello " + name;
Enter fullscreen mode Exit fullscreen mode

 

Arrow Function Syntax

For single argument and expression

const functionName = argument => expression;
Enter fullscreen mode Exit fullscreen mode

For multiple arguments and expressions

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

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!
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Example 4: Arrow function with one statement

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

const newUser = () => console.log("Welcome!");
newUser(); // Welcome!
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

 

this with arrow functions

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

With regular function

Inside of regular functions, 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();
Enter fullscreen mode Exit fullscreen mode

Output

22
undefined
Window {}
Enter fullscreen mode Exit fullscreen mode

With arrow function

However, there is no binding of this with arrow functions. So with arrow functions, 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();
Enter fullscreen mode Exit fullscreen mode

Output

22
22
User { name: 'Moz', age: 22, sayAge: [Function] }
Enter fullscreen mode Exit fullscreen mode

 

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 }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 ]
Enter fullscreen mode Exit fullscreen mode

 

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
Enter fullscreen mode Exit fullscreen mode

2. You cannot use the arrow function as a constructor

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

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.

 

Conclusion

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.
Thanks for reading!

💻 Happy Coding

Top comments (0)