We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Anonymous Functions

Anonymous functions are true to form in that they have no name. They're useful when defining a function that will only be used once or to create a quick closure.

Let's say we have a function conversions that accepts another function, converter as input:

function conversions(converter, x, y, z) {
  const convertedX = converter(x);
  const convertedY = converter(y);
  const convertedZ = converter(z);
  console.log(convertedX, convertedY, convertedZ);
}

We could define a function normally and then pass it in by name... but if we only want to use it in this one place, we can define it inline as an anonymous function:

// using a named function
function double(a) {
  return a + a;
}
conversions(double, 1, 2, 3);
// 2 4 6
// using an anonymous function
conversions(
  function (a) {
    return a + a;
  },
  1,
  2,
  3,
);
// 2 4 6

Assignment

Complete the printReports function. It takes a sequence of messages, intro, body, and outro. It should call printCostReport once for each message, in order.

For each call to printCostReport, you should pass:

  • an anonymous function that calculates the cost of a message as an integer
  • the message itself

The cost for each type of message is calculated like this:

  • Intro: 2x the message length
  • Body: 3x the message length
  • Outro: 4x the message length

Use the built-in length property to get the length of a string:

const helloLen = "hello".length;
// helloLen = 5