- 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.3 Function Literals
Let us continue the example of the preceding section. Suppose we want to multiply all array elements by 10. Of course, we can write a function
function multiplyBy10(x) { return x * 10 }
Now we can call:
result = [0, 1, 2, 4].map(multiplyBy10)
But it seems a waste to declare a new function just to use it once.
It is better to use a function literal. JavaScript has two syntactical variants. Here is the first one:
result = [0, 1, 2, 4].map(function (x) { return 10 * x })
The syntax is straightforward. You use the same function syntax as before, but now you omit the name. The function literal is a value that denotes the function with the specified action. That value is passed to the map method.
By itself, the function literal doesn’t have a name, just like the array literal [0, 1, 2, 4] doesn’t have a name. If you want to give the function a name, do what you always do when you want to give something a name—store it in a variable:
const average = function (x, y) { return (x + y) / 2 }