Home > Articles

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

This chapter is from the book

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