All you need to know about JavaScript arrow functions

Last updated: September 27, 2022.

Arrow functions were introduced to the JavaScript language in the major ES6 upgrade (2015) that transformed JavaScript from a lightweight scripting language to a modern programming lanugage.

Arrow functions enable the writing of anonymous functions using far less code than is necessary for normal functions.

Arrow functions and normal functions are often interchangeable. But there are three important functional differences between them:

  • Arrow functions return a value by default (if there is a single function statement)
  • The meaning of the keyword this is different in arrow functions
  • Arrow functions are always anonymous (though can be referenced if within a function expression)

Before taking a look at these these differences, let’s take a look at the arrow function syntax.

Arrow function syntax

Below is the syntax for an arrow function and below it a normal function that would behave in the same way:

// Arrow function
(param1) => {  
return param1+param1
}

// Normal function
function (param1) { 
return param1+param1
}

Both of these functions take a parameter x and the value of x+x.

Note that the arrow function has no name (and, for equivalence, the normal function is also written without a name). This is a feature of arrow functions: arrow functions are always anonymous.

To reference the arrow function above, we have to save it in a variable as a function expression. Now, we can call the arrow function, passing in our arguments (as per a regular function):

// Arrow function
const arrowFunc = (param1) => {  
return param1+param1
};

let x=1;
arrowFunc(x) // Result: 2

A very useful feature of arrow functions is we can write more efficient syntax by condensing the writing of functions:

  • Curly braces {} can be removed and the function statement written after the arrow (=>)
  • Arrow functions can automatically return a value so the return keyword can sometimes be omitted (more below)
  • When there is only one parameter, the parameter parentheses () can be removed

Thus, the function above can be condensed to:

const arrowFunc = param1 => param1+param1;

let x=1;
arrowFunc(x) // Result: 2

Now, let’s take a look at three fundamental aspects that differentiates arrow functions from normal functions.

Three features of arrow functions

1️⃣: An automatic return value (sometimes)

Usefully, arrow functions automatically return a result if they contain only one function statement and the statement is written after the arrow on one line:

const x = 1

// Arrow functions
const arrowFunc1 = param1 => param1+param1;
const arrowFunc2 = param1 => { param1+param1 }

arrowFunc1(x) // 2
arrowFunc2(x) // undefined

Normal functions, on the other hand, always require the inclusion of the return keyword.

2️⃣: The meaning of the word this

Though arrow functions can make our syntax more concise, their use can be problematic when they contain the keyword this. This is because, when used in arrow functions, this refers to the parent of the containing object. In normal functions, this refers to directly to the containing object.

Unless there is nesting, the parent of the containing object of an arrow function will usually be the global window object.

This can make the use of arrow functions in JavaScript objects problematic when wanting to reference the object itself or another property within the object

// With an arrow function
const obj = {
    age: 33,
    name: () => {
        console.log(this);
        console.log(this.age);
    }
}

// With a normal function
const obj2 = {
    age: 33,
    name: function() {
        console.log(this);
        console.log(this.age);
    }
}
        
obj.name() 
// Returns window object and undefined
obj2.name()
//Returns obj and 33

3️⃣: Anonymity

As mentioned when outlining the basic syntax of arrow functions, they are always anonymous: arrow functions themselves do not have a name, unlike normal functions.

But arrow functions can be referenced when saved inside a variable as a function expression.

Use cases where arrow functions shine ☀️

Given their features, arrow function are ideal for defining callback functions within higher-order method, i.e. in functions that accept functions, that would normally become very messy. Not only that, but arrow functions are more functionally appropriate because in such cases, a return value is often expected. Arrow functions can return one by default.

Let’s take a look at two such common use cases where arrow functions prove very useful.

Example #1: Shortening setTimeout()

The setTimeout() method takes two parameters: (1) an anonymous callback function; (2) a delay in calling the function in milliseconds.

Using a regular function, we could define a named function and then reference it within setTimeout():

setTimeout(runAlert, 5000);

function runAlert() {
   alert("Function executed")
}

This is a perfectly functional solution (and even preferable if we want to call the runAlert function multiple times because we can reference it).

But often with setTimeout, we are defining a function that is only to be used within setTimeout. So we could choose to define it as an anonymous function directly as the first argument.

With a normal function, this would get quite messy:

setTimeout(function() {
alert("Function executed")
}
, 5000);

This solution spans over several lines and is a little tricky to read. With an arrow function, we can condense this syntax to a single line.

setTimeout( () => alert("Function executed"), 5000);

Example #2: Making use of an automatic return value using filter()

Let’s now take a look at why the default return value of arrow function can be useful with an example using the filter() method.

The filter() method is available for array objects and accepts a callback function as a parameter. The callback function is run on every element in the array upon which filter() is called. For each application of the callback function, filter() expects a returned value of true or false. If true, an array element is kept, if false, it is discarded. Only kept element are returned as a result of applying the filter() method to an array.

Using a normally defined function, running the filter() method looks something like below.

The return keyword is included to make sure that true or false is returned by the callback function.

const Array = [1,2,3];

const newArray = Array.filter(callbackFunction);
 
function callbackFunction(arrayElement) {
return arrayElement > 1
}

console.log(newArray);// [2,3]

With the arrow function syntax, we can greatly reduce the necessary code:

const Array = [1,2,3];

const newArray = Array.filter( arrayElement => arrayElement > 1 );

console.log(newArray);// [2,3]

Now that’s efficient!

Summary

Arrow functions allow us to efficiently define anonymous functions, which can be particularly useful when writing callback functions.

But they can also be used more generally within a script when stored within a function expression (though, unlike normal function, only after they are defined).

But beware when using the keyword this within arrow functions! It refers to the parent of the functions containing object. So it is usually best to avoid their use within JavaScript objects.