- Arrow functions creates a function that accepts arguments
arg1..argN
, then evaluates the expression
on the right side with their use and returns its result.let func = (arg1, arg2, ..., argN) => expression;
- In other words, it’s the shorter version of:
let func = function(arg1, arg2, ..., argN) {
return expression;
};
- If the function only has one line in the curly brackets, you can omit the curly brackets
{}
.
- If the function only takes one parameter, you can also omit the brackets around the parameter
()
.
- If your function needs to return a value, and contains only one line, you can also omit the
return
statement.let age = prompt("What is your age?", 18);
let welcome = (age < 18) ?
() => alert('Hello!') :
() => alert("Greetings!");
welcome();
- For multiline arrow functions:
let sum = (a, b) => { // the curly brace opens a multiline function
let result = a + b;
return result; // if we use curly braces, then we need an explicit "return"
};
alert( sum(1, 2) ); // 3