JavaScript Arrow function
In this article, we will learn about JavaScript Arrow function. Arrow functions were introduced in ES6 / ECMAScript 2015 and provides a concise way to write functions in JavaScript.
- Set a default parameter value for a JavaScript function
- Replace multiple strings using Split and Join functions
- How to use Map, Filter, and Reduce in JavaScript
Normal function``` function calculate() { //... }
**Arrow function**```
const calculate = () => {
//...
}
- Visually, An arrow function expression has a shorter syntax than a function expression.
- Unlike a regular function, an arrow function does not bind
this
. Instead,this
is bound lexically (i.e.this
keeps its meaning from its original context). - These function expressions are best suited for non-method functions and they cannot be used as constructors.
- No Parameters function
- Single Parameter function
- Multiple Parameter function
- Single line No Parameter function (Implicit return)
- Single line Single Parameter function (Implicit return)
- Single line Multiple Parameters function (Implicit return)
1. No Parameters function
If you don’t have any parameters in function and you want to use the arrow function then just use ()
.
let getDefaultValue = () => {
...
return {
number: 50,
base: 10
}
}
getDefaultValue(); // Output: { number: 50, base: 10 }
2. Single Parameter function
If Method contains single parameter then you can directly write the parameter without having ()
. You can also use ()
as well.
let getDefaultValue = number => {
...
return {
number: number,
base: 10
}
}
getDefaultValue(20); // Output: { number: 20, base: 10 }
3. Multiple Parameter function
If you have a method which contains multiple parameters then you can define function like below.
let getDefaultValue = (number, base) => {
...
return {
number: number,
base: base
}
}
getDefaultValue(40, 20); // Output: { number: 40, base: 20 }
4. Single line No Parameter function (Implicit return)
Arrow functions allow you to have an implicit return that means values are returned without having to use the return keyword. In other words, you can say single line function.
let getDefaultValue = () => ({
number: 50,
base: 10
})
getDefaultValue(); // Output: { number: 50, base: 10 }
5. Single line Single Parameter function (Implicit return)
Same as above, if you have single parameter then you can write the function as below.
let getDefaultValue = number => ({
number: number,
base: 10
})
getDefaultValue(70); // Output: { number: 70, base: 10 }
6. Single line Multiple Parameters function (Implicit return)
Let’s say if you have multiple parameters then your function should look like below.
let getDefaultValue = (number, base) => ({
number: number,
base: base
})
getDefaultValue(80, 35); // Output: { number: 80, base: 35 }
Here is another example for you.
let calculate = (value1, value2) => value1 + value2
calculate(5, 7); // Output: 12
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!