4 Ways to write Arrow Function in Javascript
Authored By: Sanjeet Tripathi
An Arrow function is an alternative to traditional function declaration in javascript as well as an extension of an anonymous function. It is an easy and efficient feature of Javascript which is used widely in all its framework like React, Angular, and Vue.Js
Do not get confused between the Arrow function and Annonymous Function, as a matter of fact, they both are very much different. See Below
//Anonymous Function
function (x,y){
return x+y
}
//Arrow function
(x,y) => x+y
Learn the concepts of Javascript with YourEngineer
There are different ways to write Arrow Function in Javascript, it is all based on different conditions, and these different approaches reduce the line in coding. Let’s see below all the approaches.
The Traditional way to write Arrow Function
The Arrow function does not use any keyword to declare the function, you can simply write a parenthesis for the arguments and an Arrow sign like this => and then simply write the function body. see an example below
//Traditional way to write Arrow Function
let travelPlan = (location, price) =>{
console.log("If you want to travel " + location + " it will cost you " + price + " dollars")
}
travelPlan("Paris", 10000)
Writing Arrow Function with two parameters
When there are two parameters in the arrow function you can simply write it like the below.
//Arrow function with two parameters
let addition = (a,b) =>{ return a+b }
addition(30,70)
Learn the concepts of Javascript with YourEngineer
Writing Arrow Function with Zero Parameter
In cases where there is no parameter in the function, you can simply write parenthesis, arrow sign, and function body. See example below
//Arrow Function with no parameter
let greeting = () =>{ return "Hello and Good Morning Everyone" }
travelPlan("Paris", 10000)
Writing Arrow Function with single parameters
In the cases, where there is only one parameter in the function, one can remove the parenthesis too. See the example below.
//Arrow function with two parameters
let travelLocation = location =>{ console.log("Lets go to " + location) }
travelLocation("Paris")
The Arrow function provides efficiency and effectiveness to the program, that’s why it is considered one of the best features of Javascript
Keep Coding!!
What is YourEngineer?
YourEngineer is the first Engineering Community Worldwide that focuses on spreading Awareness, providing Collaboration and building a focused Career Approach for Engineering Students.
Deep dive into upskilling with Javascript
Join millions like you
