DEV Community

Cover image for Arrow Functions
Vivek Alhat
Vivek Alhat

Posted on

Arrow Functions

Arrow functions were added in javascript as a part of the ES6 javascript revision. Arrow functions are also called 'Fat Arrow' functions. The arrow function syntax is used to write concise code.

Usually while writing a function in javascript, we prefix it with the function keyword. The traditional method of writing functions is kind of messy. Fat arrow syntax helps to write compact and clean code.

It is called a fat arrow because of the syntax =>.

Let's discuss the usage of arrow functions with the help of a few examples below.

In general, a function to add two numbers and return the result is written as follows,

function addition (num1, num2) {
return num1 + num2;
}
Enter fullscreen mode Exit fullscreen mode

We can simplify the above code and make it look cleaner with the help of a fat arrow.

const addition = (num1, num2) => {
return num1 + num2;
}
Enter fullscreen mode Exit fullscreen mode

Here, addition is a constant function that takes two parameters and returns a result.

While using arrow functions, if the function has only a single return statement then we can completely eliminate curly braces and a return keyword.

const addition = (num1, num2) => num1 + num2;
Enter fullscreen mode Exit fullscreen mode

Our code looks cleaner as compared to traditional functions.
We can remove curly braces and a return keyword only if there is a single return statement.

Similarly, if a function takes only one input parameter then it is completely ok to remove surrounding parentheses. Let's see it in action below.

const multiply = num => num * 2;
Enter fullscreen mode Exit fullscreen mode

The above function takes only a single input parameter num and returns the result.

Arrow functions are called similarly to traditional functions.

console.log(multiply(2));
Enter fullscreen mode Exit fullscreen mode

In conclusion, an arrow function provides an alternative way to write shorter and cleaner code.

Top comments (0)