All about Arrow functions in Javascript

What are Arrow functions?
Arrow functions in JavaScript are a shorter way of writing functions. They were introduced in ES6 (ECMAScript 2015) and provide a more concise syntax compared to traditional function expressions.
The basic syntax of an arrow function is as follows:
(parameter1, parameter2, ...) => { statements }
Here's an example of an arrow function that takes two parameters and returns their sum
const add = (a, b) => a + b;
The Motivation behind arrow functions
The introduction of arrow functions in JavaScript was motivated by a desire to simplify function syntax and provide more predictable behavior for this
keyword. Arrow functions were designed to address issues with traditional JavaScript functions such as unpredictable this
binding, verbosity, and variable shadowing, making it easier to write and maintain complex JavaScript applications.
Lexical this
binding
//Traditional Function Example
const person = {
firstName: "John",
lastName: "Doe",
getFullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.getFullName()); // "John Doe"
In the example above, getFullName
is a method on the person
object. When getFullName
is called, this
refers to the person
object.
// Arrow Function Example
const person = {
firstName: "John",
lastName: "Doe",
getFullName: () => {
return this.firstName + " " + this.lastName;
}
};
console.log(person.getFullName()); // "undefined undefined"
In this example, getFullName
is an arrow function. When getFullName
is called, this
refers to the global object instead of the person
object. This is because arrow functions do not have their own this
value and instead inherit the this
value from the surrounding scope.
Arrow functions have a lexical this
binding, which means that the value of this
inside an arrow function is inherited from the surrounding scope. This eliminates the need to use the bind
, call
, or apply
methods to preserve the value of this
in complex object hierarchies.
Concise syntax
Arrow functions have a more concise and readable syntax compared to traditional JavaScript functions. They have a shorter syntax, and the function body is expressed on a single line. This makes the code more readable and easier to maintain.
//Traditional Function Example:
function double(x) {
return x * 2;
}
console.log(double(5)); // 10
//Arrow Function Example:
const double = x => x * 2;
console.log(double(5)); // 10
Implicit return
Arrow functions have an implicit return statement, which means that you don't need to use the return
keyword to return a value. This further simplifies the syntax and reduces the number of lines of code required.
// Traditional function with explicit return statement
function add(a, b) {
return a + b;
}
// Arrow function with implicit return
const multiply = (a, b) => a * b;
// Usage
const sum = add(2, 3); // sum = 5
const product = multiply(4, 5); // product = 20
Note that the implicit return syntax only works if the expression being returned is a single expression. If you need to perform more complex operations or have multiple statements, you'll need to use curly braces and an explicit return statement, even in an arrow function.
Different ways to write Arrow functions
Arrow functions can be written in a few different ways, depending on the syntax and requirements of the function. Here are some examples of different ways to write arrow functions in JavaScript:
//Arrow function with a single argument
const squareArrow = x => x * x;
//Arrow function with multiple arguments
const sumArrow = (a, b) => a + b;
//Arrow function with no arguments
const greetArrow = () => console.log('Hello!');
//Arrow function with a block statement
const sumArrayArrow = numbers => {
let sum = 0;
for (let number of numbers) {
sum += number;
}
return sum;
};
Enhanced Performance
Arrow functions have enhanced performance over traditional JavaScript functions. They have a simpler structure, which makes them easier to parse and execute, leading to improved performance.
There have been various benchmarks conducted that demonstrate that arrow functions are generally faster than traditional JavaScript functions.
In a benchmark test conducted by JSBench & jsPerf platform, arrow functions were found to be faster than traditional functions in both creation time and execution time. The test measured the performance of different function types for various operations, such as function creation, function invocation, and iteration. Arrow functions consistently outperformed traditional functions in all the tests.
Other important things to know about Arrow Functions
How do arrow functions handle the arguments object?
Arrow functions handle the arguments
object differently than regular functions. In an arrow function, the arguments
object refers to the arguments of the enclosing scope, not the arrow function itself.
function average() {
const args = Array.from(arguments);
const sum = args.reduce((total, val) => total + val);
return sum / args.length;
}
console.log(average(1, 2, 3)); // Output: 2
const averageArrow = () => {
const args = Array.from(arguments);
const sum = args.reduce((total, val) => total + val);
return sum / args.length;
}
console.log(averageArrow(1, 2, 3)); // Throws a ReferenceError: arguments is not defined
In this example, we define a average
function that uses the arguments
object to calculate the average of its arguments. We also define an arrow function averageArrow
that attempts to do the same thing, but it throws a ReferenceError
because the arguments
object is not defined in arrow functions. To fix this, we can use the rest parameter syntax instead.
const averageArrow = (...args) => {
const sum = args.reduce((total, val) => total + val);
return sum / args.length;
}
console.log(averageArrow(1, 2, 3)); // Output: 2
How do arrow functions handle function names and recursion?
Arrow functions can have names, but the name does not become a variable in the function's scope like it does in a traditional function. This means that arrow functions are not suitable for recursion, because they cannot refer to themselves by name.
Here's an example that demonstrates the difference in behavior between traditional and arrow functions.
// Traditional function with recursion
function factorial(n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
// Arrow function with the same logic
const factorialArrow = (n) => {
if (n <= 1) {
return 1;
} else {
return n * factorialArrow(n - 1); // TypeError: factorialArrow is not a function
}
};
console.log(factorial(5)); // logs 120
console.log(factorialArrow(5)); // TypeError: factorialArrow is not a function
In this example, we have a traditional function factorial
that calculates the factorial of a number using recursion.
However, when we call factorialArrow
recursively, we get a TypeError
because the function's name does not become a variable in the function's scope as it does in a traditional function. To make recursion work with an arrow function, we would need to use a variable instead of a function name to refer to the function.
So while arrow functions can have names, they are not suitable for recursion or other cases where the function needs to refer to itself by name.
Arrow functions are a powerful and useful addition to the JavaScript language. They provide a more concise syntax for writing functions, making code easier to read and write. They also offer several benefits over traditional JavaScript functions, including lexical scoping of the this
keyword, no arguments
object, and implicit return statements.
While arrow functions may not be suitable for all situations, they are a great tool to have in your JavaScript toolbox. By understanding the differences between traditional and arrow functions, you can choose the best approach for your specific use case and write more efficient and effective JavaScript code.
Subscribe to my newsletter
Read articles from Sudhakar Patil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Sudhakar Patil
Sudhakar Patil
Experienced .NET developer, with deep understanding of the intricacies of the platform having worked on a wide range of projects.