JS Arrow Functions Made Easy

Photo by Christopher Robin Ebbinghaus on Unsplash

Disclaimer

This article is for all the developers scratching their head around the arrow functions. I hope this article helps you to clear your doubts and help you better understand the Arrow Functions.

The Arrow Functions were introduced in ECMAScript 6 also known as ES6 or ECMAScript 2015. They provide a shorter and a much efficient syntax.

Frameworks like React use ES6 and so it becomes really important to learn and understand about these arrow functions.

I will walk you through the syntax of arrow functions comparing them with the vanilla JS functions.

Let’s take an example of a simple addition function and try to understand the syntax.

// Vanilla JS add function with no parameters
function addFunc(){
var a = 2;
var b = 3;
return a+b;
}
// returns 5
// Similar function in ES6
addFunc = () => {
var a = 2;
var b = 3;
return a+b;
}

On comparing the above code we can see that to define a function in ES6 we do not need to use the function keyword.

Modifying the above example

// Vanilla JS
function addFunc (b){
var a = 2;
return a+b;
}
addFunc(3) // returns 5
// ES6
addFunc = (b) => {
var a = 2;
return a+b;
}
addFunc(3) // returns 5

The above function has only one parameter hence we can also write it as follow

addFunc = b => {
var a = 2;
return a+b;
}
addFunc(3) // return 5

Again let’s see what it looks like if we only have the return statement in the function. For the same example we will pass a as a parameter too and simply return the addition of the two parameters passed.

// Vanilla JS
function addFunc(a,b){
return a+b;
}
// ES6
addFunc = (a,b) => a+b

From the above example we can see that we don’t need the parenthesis when we are only returning a value, and there aren’t any other statements in the function.

I hope this comparisons makes it easy for you understand Arrow Functions. If you have an questions, feel free to reach out to me. I would enjoy listening to your feedback. You can hit me up on Twitter @a_harshil1712