JavaScript Arrow Function allows you to create functions in a cleaner way compared to regular functions.
Arrow functions allow us to write shorter function syntax.
Arrow functions were introduced in ES6.
In this tutorial, you will learn about JavaScript arrow function with the help of examples.
Example
This function
// function expression
let x = function(x, y) {
return x * y;
}
can be written as
// using arrow functions
let x = (x, y) => x * y;
using an arrow function.
Arrow Function Syntax
let myFunction = (arg1, arg2, ...argN) => {
statement(s)
}
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
Example 1: Arrow Function with No Argument
let greet = () => console.log('Hello');
greet(); // Hello
If a function doesn’t take any argument, then you should use empty parentheses as shown in above example.
If the function has only one statement, and the statement returns a value, you can remove the brackets and the return
keyword.
hello = () => "Hello World!";
Above example works only if the function has only one statement.
Example 2: Arrow Function with One Argument
If a function has only one argument, you can omit the parentheses as shown in below example.
let greet = x => console.log(x);
greet('Hello'); // Hello
Example 3: Arrow Function as an Expression
You can also dynamically create a function and use it as an expression as shown in below example.
let age = 5;
let welcome = (age < 18) ?
() => console.log('Baby') :
() => console.log('Adult');
welcome(); // Baby
Example 4: 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);
console.log(result1); // 12
Comparing traditional functions to arrow functions
// Traditional Anonymous Function
function (a){
return a + 100;
}
// Arrow Function Break Down
// 1. Remove the word "function" and place arrow between the argument and opening body bracket
(a) => {
return a + 100;
}
// 2. Remove the body braces and word "return" -- the return is implied.
(a) => a + 100;
// 3. Remove the argument parentheses
a => a + 100;