Functional Encapsulation

The fact that functions create scope and that they can be nested allow us to achieve Object-Oriented Programming (OOP)like encapsulation and information hiding:

A function can bundle several related functions and share variables declared in the parent function. (Similar to what a class does in OOP.)

Consider the following case: we had a handful of globally-scoped variables; we could wrap the entire content of script.js into a function and then call that function to put its content in action.

function tictactoe() {
  // copy over the content of script.js
}

tictactoe();

We can also use a Self-Executing Anonymous Function (also known as Immediately Invoked Function Expression, or IIFE):

(function () {
  // copy over the content of script.js
})();

This strategy used to be a pervasive pattern employed by JavaScript programmers to create OOP-like encapsulation and prevent polluting the global scope.

IIFE

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as defined.

(function () {
    // statements
})();

It contains two major parts:

  1. The anonymous function enclosed within the Grouping Operator ().
  2. The following () creates the immediately invoked function expression.

In Modern JavaScript, you should use Modules and Classes instead of IFFEs.

JavaScript Modules and Classes will be explored in a later chapter.