Page 126 - JavaScript
P. 126
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 type of function into constant variables:
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 function body doesn't consist of a single expression, it must be surrounded by brackets and
use an explicit return statement for providing a result:
(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 indicate that the opening and closing brackets are part of the object literal,
i.e. they are not delimiters of the function body.
Lexical Scoping & Binding (Value of "this")
Arrow functions are lexically scoped; this means that their this Binding is bound to the context of
the surrounding scope. That is to say, whatever this refers to can be preserved by using an arrow
function.
Take a look at the following example. The class Cow has a method that allows for it to print out the
sound it makes after 1 second.
https://riptutorial.com/ 83

