JavaScript Arrow Function
Arrow function is one of the features introduced in the ES6 version of
JavaScript.
It allows you to create functions in a cleaner way compared to regular
functions.
For example,
This function
let x = function(x, y) {
return x * y;
}
can be written as
let x = (x, y) => x * y;
using an arrow function.
Arrow Function Syntax
The syntax of the arrow function is:
let myFunction = (arg1, arg2, ...argN) => {
statement(s)
}
Here,
myFunction is the name of the function
arg1, arg2, ...argN are the function arguments
statement(s) is the function body
If the body has single statement or expression, you can write arrow
function as:
let myFunction = (arg1, arg2, ...argN) => expression
Arrow Function with No Argument
If a function doesn't take any argument, then you should use empty
parentheses.
let greet = () => [Link]('Hello');
greet(); // Hello
Arrow Function as an Expression
let age = 5;
let welcome = (age < 18) ?
() => [Link]('Baby') :
() => [Link]('Adult');
welcome(); // Baby
Multiline Arrow Functions
If a function body has multiple statements, you need to put them inside curly
brackets {}.
let sum = (a, b) => {
let result = a + b;
return result;
}
let result1 = sum(5,7);
[Link](result1); // 12
Arguments Binding
Regular functions have arguments binding.
That's why when you pass arguments to a regular function, you can
access them using the arguments keyword.
let x = function () {
[Link](arguments);
}
x(4,6,7); // Arguments [4, 6, 7]
Arrow functions do not have arguments binding.
When you try to access an argument using the arrow function, it will give
an error.
let x = () => {
[Link](arguments);
}
x(4,6,7);
// ReferenceError: Can't find variable: arguments
To solve this issue, you can use the spread syntax.
let x = (...n) => {
[Link](n);
}
x(4,6,7); // [4, 6, 7]