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

Immediate Invocation

You can immediately invoke a function after defining it using the not-at-all-hard-to-pronounce acronym "IIFE" (Immediately Invoked Function Expression).

(function () {
  console.log("JavaScript: at least it's not Java");
})();
// JavaScript: at least it's not Java

They can also return values and take arguments:

const result = (function (a, b) {
  return a + b;
})(1, 2);

console.log(result);
// 3

The function is defined and then immediately called. It looks nasty, but it's occasionally useful for a couple of reasons:

  • Scope: It has its own scope
  • Expression: Can be convenient for computing a value as a single expression (like above)
  • Async: Can be used to quickly run code in an async function (we'll cover this later)

Assignment

Run the given code. Notice that the total variable doesn't store the resulting number, but is actually a function!

Wrap it in an IIFE so that the total variable is calculated immediately using the following parameters:

  • numMessages: 100
  • bytesPerMessage: 24