concept immediate function in category javascript

appears as: immediate functions, n immediate function, immediate function
Secrets of the JavaScript Ninja, Second Edition

This is an excerpt from Manning's book Secrets of the JavaScript Ninja, Second Edition.

When we want to make a function call, we use an expression that evaluates to a function, followed by a pair of function call parentheses, which might contain arguments. In the most basic function call, we put an identifier that evaluates to a function, as on the left side of figure 3.5. But the expression to the left of the calling parenthesis doesn’t have to be a simple identifier; it can be any expression that evaluates to a function. For example, a simple way to specify an expression that evaluates to a function is to use a function expression. So on the right side of figure 3.5, we first create a function, and then we immediately invoke that newly created function. This, by the way, is called an immediately invoked function expression (IIFE), or immediate function for short, and is an important concept in JavaScript development because it allows us to mimic modules in JavaScript. We’ll focus on this application of IIFEs in chapter 11.

Up to ES6, JavaScript didn’t offer a higher-level, built-in feature that allows us to group related variables in a module, namespace, or package. So in order to tackle this problem, JavaScript programmers have developed advanced code modularization techniques that take advantage of existing JavaScript constructs, such as objects, immediate functions, and closures. In this chapter, we’ll explore some of these techniques.

  • Our countClicks function is called only in this one place, so instead of defining a function and then calling it in a separate statement, we’ve used an immediate function, or an IIFE (presented in chapter 3), to define and immediately invoke the countClicks function.