Introduction
suggest changeThis page is about arrow syntax, not functions in general. Functions may be written with =>, sometimes called a lambda. The old Common Lisp documentation link for that term is gone.
The simplest form of an arrow function has its arguments on the left side of => and the return value on the right side:
item => item + 1 // -> function(item){return item + 1}
This function can be immediately invoked by providing an argument to the expression:
(item => item + 1)(41) // -> 42
If an arrow function takes a single parameter, the parentheses around that parameter are optional. For example, the following expressions assign the same kind of function to constants:
const foo = bar => bar + 1;
const bar = (baz) => baz + 1;
However, if the arrow function takes no parameters, or more than one parameter, a new set of parentheses must encase all the arguments:
(() => "foo")() // -> "foo"
((bow, arrow) => bow + arrow)('I took an arrow ', 'to the knee...')
// -> "I took an arrow to the knee..."
If the body is not a single expression, surround it with braces and use an explicit return:
(bar => {
const baz = 41;
return bar + baz;
})(1); // -> 42
If the arrow function’s body consists only of an object literal, this object literal has to be enclosed in parentheses:
(bar => ({ baz: 1 }))(); // -> Object {baz: 1}
The extra parentheses show that the braces belong to the object literal. They are not the function body.