Photo by Gioele Fazzeri on Unsplash
Arrow functions in JavaScript
Let's understand Arrow Functions in JavaScript and demystify their What? Why? and When?
Hello, fellow devs ๐
In this blog, we will talk about Arrow Functions in JavaScript. If you're new to JavaScript then you'll probably be confused with the functions.
- What are Arrow Functions? Why two Syntaxes for functions?
- How do you decide where not to use the new Syntax and when to replace the old syntax with the newer one.
I'll try to answer the above questions below, So let's begin:-
๐ค What are Arrow Functions
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
from mdn docs
So by this definition, we can say that arrow functions don't replace traditional functions but it's a choice given to developers to use this new Syntax where possible to make their code clean and short.
So what do I mean by clean and short, here's an example:
// Traditional Anonymous Functions
function (num){
return num * num;
}
function (num1*num2){
return num1 * num2;
}
// Newer Syntax with Arrow Functions
// doesn't need parenthesis incase of a single parameter
// doesn't need explicit return keyword incase of single expression
num => num * num;
(num1,num2) => num1 * num2;
// Traditional Anonymous Function (no arguments)
let num1 = 5;
let num2 = 6;
function (){
return num1 * num2;
}
// Newer Syntax with Arrow Function (no arguments)
let num1 = 5;
let num2 = 6;
() => num1 * num2;
Now let's see for named functions.
// Traditional Function
function square (num){
return num * num;
}
// Arrow Function
const square = num => num * num;
So that's how you change your traditional functions to Arrow functions.
๐ Features
Here are some features for Arrow Functions, you get into the habit of using these and they make your code look more readable and concise.
parentheses
are optional in the case of a single parameter.const square = num => num * num;
parentheses
are a must when there is more than one parameter.const multiply = (num1 , num2) => num1 * num2;
Explicit
return
keyword is not required for a single expression in the function body.return
keyword is required when there are multiple statements in the function body.const fullName = () => { const name = "Shivam" + " " + "Pandey"; return name; } console.log(fullName()); //output: Shivam Pandey
To return an
object
notation, wrap it with parentheses.const getNameObj = (firstName,lastName) => ({firstName,lastName});
๐ฏ When to use Arrow Functions?
Yes, you got that right. There are certain places where you can use Arrow functions instead of traditional functions, But not everywhere. So let's first see when you should use Arrow functions.
- Callback functions:
In JavaScript, there are many places where we need to write anonymous callback functions like web APIs (setTimeout, setInterval, etc.) or in Higher-Order Functions (map, sort, reduce, etc.)
// webAPIs
setTimeout(() => {
console.log("I'll get logged first");
},0);
// Higher Order Functions.
const numsArr = [1,2,3,4,5,6];
const squareAll = () => numsArr.map(num => num * num);
const getEvens = () => numsArr.filter(num => num % 2 === 0);
- Promise Chaining
The Promise Chaining could look very messy with repetitive function
and return
keywords and here we can make use of our beloved Arrow Functions.
// Promise Chaining with traditional functions
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000);
}).then(function(result) {
return result * 2;
}).then(function(result) {
return result * 2;
}).then(function(result) {
alert(result); // 4
return result * 2;
});
// Promise Chaining with Arrow Functions
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000))
.then((result)=> result * 2)
.then((result)=> result * 2)
.then((result)=>alert(result)); //4
๐ค Limitations
Well, it's not all Roses and Sunshine, there are certain limitations to Arrow Functions too.
- this
Unlike traditional functions that have their own scope
and this
, Arrow functions don't have their own scope
and this
, Arrow functions use lexical scoping for scope
and this.
Let's see this with an example:
const obj = { // does not create a new scope
name: 'Shivam',
printName1: () => console.log(this.i, this),
printName2: function() {
console.log(this.i, this);
}
}
obj.printName1(); // prints undefined, Window {...} (or the global object)
obj.printName2(); // prints 10, Object {...} (or the obj object)
- call, apply and bind
Because of the limitations of scope
and this
, Arrow functions shouldn't be used for the call, apply, and bind methods.
Conclusion
That's pretty much it for Arrow functions. Here we talked about the Syntax and when and where to replace traditional functions with Arrow functions. It is obvious that they make our code more readable and short to write but the major limitations with the scope
and this
makes it not a complete replacement for traditional functions. So now you know when and where to use Arrow function over Traditional Functions and where not to use them.
Thanks for reading the blog please feel free to comment below for the appreciation as well as corrections.