Arrow functions 🏹 were introduced in ES6 – the newer version of JavaScript, which does all the same tasks as a normal function (defined in our previous chapters) would do. The only difference is that they have a shorter syntax.
ECMAScript 2015 or better known as ES6 is the newer published version of JavaScript that we all use today. ES6 introduced a new way of defining a function in JavaScript that has a shorter syntax.
Syntax:
const functionName = (params) => {
// Steps or code to be executed
};
The above syntax is explained as follows:
- A function having name functionName is created.
- The parameter called params is inside the parenthesis ( ).
- The actual code to be executed is written inside the braces { } after the arrow =>.
NOTE: Arrow functions save us some time in creating a function because we don’t have to type the entire keyword function just to create a function. We can just put the parameters inside ( ) and use an arrow => that points to the function body covered by braces { }.
Example
const area = (length, breadth) => {
return length * breadth;
};
var areaOfABook = area(5, 4);
console.log(`The area of this book is ${areaOfABook} square cm.`);
NOTE: Don’t be confused. We just used template literals here, denoted by backticks ` `, which was explained in our 👉 JS Interpolation and Concatenation lesson.
Output
The area of this book is 20 square cm.
In this way, Arrow Functions in JavaScript help us to write functions in a quicker, concise and cooler 😎 way.