Arrow Functions in Javascript
Besides function declarations and function expressions, JavaScript also has another very concise syntax for defining a function. These functions are called arrow functions.
In this concept, we will focus on the syntax used to write an arrow function. There are differences in the way that an arrow function works, such as this binding.
Here is a comparison between a function declaration and an arrow function.
function addUpTwoNumbers(num1, num2) {
return num1 + num2;
}
// function keyword removed and => added
const addUpTwoNumbers = (num1, num2) => {
return num1 + num2;
};
Above, you will see that the arrow function syntax:
If the function body contains only a return statement, like in the example above, the {} and the return keyword can be omitted.
Recommended by LinkedIn
const addUpTwoNumbers = (num1, num2) => { return num1 + num2 };
// can be shortened to
const addUpTwoNumbers = (num1, num2) => num1 + num2;
// braces {} and return removed
In the special case of only returning an object from an arrow function, parentheses are needed around the object to be able to omit the return statement.
// explicit return of object
const addUpTwoNumbers = (num1, num2) => {
return { num1, num2 };
};
// implicit return of object
const addUpTwoNumbers = (num1, num2) => ({ num1, num2 });
The use of parenthesis around parameters depends on the number of parameters.
// one parameter does not need parenthesis
const square = num => num * num;
// two or more parameters need to be wrapped in parenthesis
const addUpTwoNumbers = (num1, num2) => num1 + num2;
Other concepts such as Rest Parameters and Destructuring can also be used with an arrow function.
ReactJS Developer @Starzplay | Building High-Performance, Scalable Web Applications | 4+ Years in Software Development
8moIt is a perfect reminder to refresh my knowledge about Arrow Functions.