Header Ads Widget

Quick Reference of Arrow Function in JavaScript




Arrow functions were introduced with ES6 as a new way of writing JavaScript functions. This post will cover basic syntax of Arrow functions, common use cases.

Note - I am putting my JavaScript Developer study notes here

Note - Please read my previous post where I have explained the basics of functions in JavaScript.
Basics of Functions in JavaScript


What is Arrow Functions?

Arrow functions, sometimes referred as Fat Arrow is a new concise way of writing functions. They utilize a new syntax, => which looks like Fat Arrow. Arrow functions are anonymous and change the way this binds in functions. By using arrow functions, we can avoid typing function and return keyword and also curly brackets.

Basic Syntax of Arrow Function with Multiple Parameters

const multiplyFunction = (x, y) => x * y;
console.log(multiplyFunction(5, 6));

Output: 30


Syntax of Arrow Function with Single Parameter

const splitString = (text) => text.split(" ");
console.log(splitString("My name is Sudipta Deb"));

Output: 
[ 'My', 'name', 'is', 'Sudipta', 'Deb' ]


Syntax of Arrow Function with No Parameter

const functionWithNoParam = () => {
console.log("This function with no parameter");
};

functionWithNoParam();

Output: 
This function with no parameter

Syntax of Arrow Function with Object return

Arrow functions can be used to return an object literal expressions. 

var funcWithObject = (empName, empNumber) => ({
empName: empName,
empNumber: empNumber,
});
console.log(funcWithObject("Sudipta Deb", 101));


Output: 
{ empName: 'Sudipta Deb', empNumber: 101 }

Use Cases for Arrow Functions

One very common use case for Arrow function is Array manipulation. In the below example, each array items will be converted to upper case.

const countries = ["India", "Canada", "Switzerland", "Germany"];
const countriesWithCaps = countries.map((country) => country.toUpperCase());

console.log(countriesWithCaps);


Output:
[ 'INDIA', 'CANADA', 'SWITZERLAND', 'GERMANY' ]

Another little advanced example is when you want to return something from an array that meets the criteria. So in the below example, I would like to return only those tasks which are completed.

const myTasks = [
{
description: "Write Blog Post",
status: "Completed",
},
{
description: "Study Architect Certification",
status: "Pending",
},
{
description: "Go for walk",
status: "Completed",
},
];

const completedTask = myTasks.filter((myTask) => myTask.status === "Completed");

console.log(completedTask);

Output:
[
{ description: 'Write Blog Post', status: 'Completed' },
{ description: 'Go for walk', status: 'Completed' }
]

Now if I want to just print the description instead of everything, we can use another Arrow Function to do that like below

const myTasks = [
{
description: "Write Blog Post",
status: "Completed",
},
{
description: "Study Architect Certification",
status: "Pending",
},
{
description: "Go for walk",
status: "Completed",
},
];

const completedTask = myTasks.filter((myTask) => myTask.status === "Completed");
completedTask.forEach((singleTask) => console.log(singleTask.description));

Output:
Write Blog Post
Go for walk


Promises and Callback

Promises make it easier to manage async code. This is the perfect situation to use Arrow function. Here is the syntax

this.doSomething().then((result) => {
this.handleResult(result);
});

Places not to use Arrow Function

Let's consider the below object which is having one method describeMe() which is returning a String. 

const Car = {
brand: "Honda",
price: 132000,
describeMe: function () {
return `I am ${brand} car with price ${price}`;
},
};

console.log(Car.describeMe());

If you execute the above code, you will get the undefined error while accessing brand and price. To solve that, let's use This now to bind brand and price with the Car object context. So now the code looks like -

const Car = {
brand: "Honda",
price: 132000,
describeMe: function () {
return `I am ${this.brand} car with price ${this.price}`;
},
};

console.log(Car.describeMe());

Output:
I am Honda car with price 132000

Now if you think of replacing describeMe function with Arrow function, it will look like below -

const Car = {
brand: "Honda",
price: 132000,
describeMe: () => `I am ${this.brand} car with price ${this.price}`,
};

console.log(Car.describeMe());

But this time you will get again the undefined error. Why???

This keyword is bound to different values based on the context in which it is called. With Arrow Function, it is little different. Here This is lexically bound i.e. it uses this from the code that contains the arrow function. So Arrow Function should not be used in Object methods.

Wrapping up

Arrow function is a great addition to JavaScript language and with this for concise code can be written.

Further Reading

Post a Comment

0 Comments