Five things about Arrow Functions
- Syntax for Arrow Function
An arrow function in JavaScript is an easier and shorter way to write a function. Instead of using the word function, you use => (an arrow).
Here’s how it works: you write the inputs (parameters) in parentheses, followed by the arrow, and then the code. For example, (x) => { return x * 2; } is a function that doubles a number.
If there’s only one input, you can skip the parentheses, like this: x => { return x * 2; }.
If the function is just one line, you can also skip the {} and the return keyword, like this: x => x * 2. Arrow functions are quick and useful, especially when working with arrays or small tasks.
function(a) {
return a+100; //traditional function
}
(a) => {
return a+100; //removed the word “function” and place arrow between
}
a => a+100; //used for formatting the output to show line by line
- Parenthesis
Parenthesis can be omitted if the Function has a single simple parameter.
If it has multiple parameters, no parameters, or default, de-structured or rest parameters, the ( ) Parenthesis around the parameter is required.
1.
function (a , b) => {
return a+b+100; //Traditional function with multiple parameters
}
(a,b) => a+b+100; //Arrow function with multiple parameters
2.
function () => {
return a+b+100; //Traditional function with no parameters
}
( ) => a+b+100; //arrow function with no parameters
- Braces
The Braces can only be omitted if the function directly returns an expression.
If the body has statements, the braces are required and so is the return keyword.
1.
function (a , b) => {
const chuck = 42; //Traditional function with multiple line body statements
return a+b+chuck;
}
2.
(a,b) => {
const chuck =42;
return a+b+chuck ;
} //Arrow function with multi-line body {} needed
- Function name
Arrow functions are not inherently associated with a name. If the arrow function needs to call itself, then use a named function.
You can also assign the arrow function to variables allowing you to refer to it, through that variable.
1.
function bob(a) => {
return a+100; //A named traditional function
}
2.
const bob2 = a => a +100;
//Anonymous arrow function assigned to a Variable
- When to use
Don’t use to add function as a property in object literal because we can not access this.
Function expressions are best for object methods. Arrow functions are best for callbacks or methods like map, reduce, or forEach.
Use function declarations for functions you’d call by name (because they’re hoisted).
Use arrow functions for callbacks (because they tend to be terser)