To encapsulate an entire JavaScript script, preventing global scope pollution and creating a private scope for its variables and functions, an Immediately Invoked Function Expression (IIFE) is commonly used.
Here is how to encapsulate an entire JavaScript script using an IIFE:
JavaScript
(function() {
// All your JavaScript code goes here.
// Variables and functions declared within this IIFE
// will be scoped locally and not pollute the global namespace.
let privateVariable = "This is a private variable.";
function privateFunction() {
console.log("This is a private function.");
}
// If you need to expose certain functionalities to the global scope,
// you can attach them to a global object (e.g., window) or return them.
window.myGlobalObject = {
publicMethod: function() {
console.log("This is a public method accessing a private variable:", privateVariable);
}
};
// You can also return an object containing public methods
// if you want to create a module-like structure.
// Example:
// return {
// exposedFunction: function() {
// privateFunction();
// }
// };
})(); // The parentheses immediately invoke the function.
Explanation:
Anonymous Function: The code is wrapped inside an anonymous function: function() { ... }.
Parentheses for Function Expression: The entire function definition is enclosed in parentheses (function() { ... }). This transforms the function declaration into a function expression.
Immediate Invocation: The trailing () immediately after the closing parenthesis ) executes the function expression.
This pattern creates a new, isolated scope for the script, ensuring that any variables or functions declared within it do not clash with other scripts on the same page or accidentally modify global objects. Only explicitly exposed elements (like window.myGlobalObject in the example) become accessible from outside the IIFE.