Arrow Functions in JavaScript

We have studied about functions in previous blog. But arrow function are special type of function which provides us clarity and make code little shorter. Let's have a very short look on how arrow function reduces boiler plate.
//Normal function
function sum (a,b) {
return a+b;
}
//Arrow function
const sum = (a,b) => a+b;
At first sight arrow function looks more complicated and scary but it's use case in javascript is huge, and once we ger clarity over it, it'll make your code 2x faster.
Arrow Function
Arrow functions are shorter way to write functions.
It uses
=>arrow syntax.It must stored in a variable (just like function expression)
It may remove
returnkeyword if only one line is present.
Syntax:
const functionName = (parameters) => {
//code
};
Behaviours while passing Parameters:
Arrow function has slight difference while having parameters. The syntax is changed only in two cases i.e. either you have single parameter or multiple parameter.
CASE 01: Single Paramater:
Unlike normal function, if there's only one parameter then no need to use
parentheses ()around it.Although it would work with them, but it's optional.
const square = num => {
return num*num;
}
console.log(square(6)); //36
CASE 02: Multiple Paramater:
- You must have to include
parentheses ()
const sum = (a,b) => {
return a+b;
}
console.log(sum(5,5)); //10;
Explicit and Implicit Return:
We already know that:
Explicit -- forcing someone
Implicit -- automatic behaviour
But how it's related to our arrow function and return keyword? Let's have a look via examples:
//Explicit return - Forcing to return using "return" keyword
const sum = (a,b) => {
return a+b;
}
console.log(sum(5,5)); //10
//Implicit return - Automatic return - No use of "return" keyword
const sum = (a,b) => a+b;
console.log(sum(5,5)); //10
Behaviour behind this:
Even if we use Explicit return the code will work perfectly fine but if we are using arrow function and we have only one line of code then it is adviced to use implicit return as it reduces code and makes it more readble.
But if we have multiple lines then it's must to use explicit return.
Major difference in Normal Function & Arrow Function
| Normal Function | Arrow Function | |
|---|---|---|
| Syntax | function f(){} |
const f = () => {} |
function keyword |
✅ Yes | ❌ No |
| Stored in variable | ❌ No | ✅ Yes |
| Hoisting | ✅ Yes | ❌ No |
return keyword |
always needed | optional if 1 line |
| Implicit return | ❌ No | ✅ Yes |
this keyword |
✅ has own this |
❌ no own this |
arguments object |
✅ Yes | ❌ No |
| Use when | general functions | short, callback functions |




