- 3.1 Declaring Functions
- 3.2 Higher-Order Functions
- 3.3 Function Literals
- 3.4 Arrow Functions
- 3.5 Functional Array Processing
- 3.6 Closures
- 3.7 Hard Objects
- 3.8 Strict Mode
- 3.9 Testing Argument Types
- 3.10 Supplying More or Fewer Arguments
- 3.11 Default Arguments
- 3.12 Rest Parameters and the Spread Operator
- 3.13 Simulating Named Arguments with Destructuring
- 3.14 Hoisting
- 3.15 Throwing Exceptions
- 3.16 Catching Exceptions
- 3.17 The finally Clause
- Exercises
3.4 Arrow Functions
In the preceding section, you saw how to declare function literals with the function keyword. There is a second, more concise form that uses the => operator, usually called “arrow”:
const average = (x, y) => (x + y) / 2
You provide the parameter variables to the left of the arrow and the return value to the right.
If there is a single parameter, you don’t need to enclose it in parentheses:
const multiplyBy10 = x => x * 10
If the function has no parameters, use an empty set of parentheses:
const dieToss = () => Math.trunc(Math.random() * 6) + 1
Note that dieToss is a function, not a number. Each time you call dieToss(), you get a random integer between 1 and 6.
If an arrow function is more complex, place its body inside a block statement. Use the return keyword to return a value out of the block:
const indexOf = (arr, value) => { for (let i in arr) { if (arr[i] === value) return i } return -1 }