Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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
  • + Share This
  • 🔖 Save To Your Account