Arrow Functions
Written By: Avinash Malhotra
Updated on
JavaScript Arrow Function
An Arrow Function in javascript is basically Function Expression, with less code and some limitations. Arrow Functions are primarily used as callback functions in javascript or function Expressions with less code.
Arrow Functions are basically Anonymous Functions used in variables or as callbacks. Arrow Function use Fat Arrows, i.e => to defined a function.
Arrow Function Example
const sayHi = ()=>"hello";
sayHi is variable name with value as arrow function. () are for parameters and "hello" is return value.
How to create arrow functions?
Arrow functions can be create using single line or multiple lines.
Single line arrow functions
Arrow functions can be written in single line without parenthesis {}. The return value is written directly without using return keyword.
const sayHi = (x)=>`hello ${x}`;
const sayBye = x=>`bye bye ${x}`;
const sum = (x,y)=>x+y;
Multiple line arrow functions
Multi line arrow function is recommended with multiple statements and then return value. Both parenthesis {} and return keyword are required.
const sayHi = ()=>{
return "hello";
};
Arrow function with single parameter
const sayHi = x=>{
return `hello ${x}`;
};
Arrow function with multiple parameters
const sum = (x,y) =>{
return x+y;
};
Use Cases
Arrow Functions are best recommended for following cases.
- Function Expressions
- Callback functions
- Events
Drawbacks
There are some cases where Arrow Functions are not recommended.
- where this keyword is required
- where arguments object is required
- where we need to create instance (constructor) of function
Arrow Function Vs Regular Functions
Here is the difference between Arrow function and Regular functions.
Property | Regular Function | Arrow Function |
---|---|---|
this keyword | supports | no support |
argument object | supports | no support |
create constructor | yes | no |
Arrow functions in Events
Arrow functions can be used in event listeners as callback where this is not required. However we can use event.target where event is parameter of arrow function.
document.querySelector("button").addEventListener("click",(e)=>{
document.querySelector("span").innerHTML="Clicked";
});
Arrow functions in Arrays
Arrow functions are always recommended in arrays as callback for sort, filter other methods. There this keyword in not required.
[1,2,3,4,5,6]
[2,4,6]
const data=[1,2,3,4,5,6];
const even=data.filter(i=>i%2==0);
console.log(data);
console.log(even);