Functional Encapsulation
The fact functions create scope and 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 allow them share variables declared in the parent function. (Similar to what a class does in OOP.)
Recall the implementation of Tic-Tac-Toe: 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 very common 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 it is defined.
(function () {
// statements
})();
It contains two major parts:
- The anonymous function enclosed within the Grouping Operator
()
. - The following
()
which 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 near future.