DEV Community

Abdullah Al Numan
Abdullah Al Numan

Posted on

6 2

What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?

In JavaScript, wrapping the entire content of a source file generally comes with immediately invoking it. The function is called an Immediately Invoked Function Expression, or IIFE. It is also called a Self-Executing Anonymous Function.

(function () {
  /* … */
})();
Enter fullscreen mode Exit fullscreen mode

It's a design pattern commonly used in the ES6 Module Pattern before ES6 modules were introduced. It helps us encapsulate data and functionality inside a module. jQuery plugins were usually created with IIFEs.

IIFEs are significant because:

  • they help with namespacing functions and variables in a library. Namespacing helps us prevent polluting the global namespace.
  • they help us control privacy of variables and functions. With an IIFE, we are able to expose only the APIs that we want to -- by returning them in an object, and hide the rest.

References

  1. IIFE
  2. Does the module pattern require the use of an IIFE?
  3. Modules (Stateful Access Control)
  4. The Power of the Module Pattern in JavaScript

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (3)

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman • Edited

The most useful thing about IIFE is variable minification. Minification tools won’t touch global variable names so it is impossible to minify global variables.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

It's a design pattern commonly used in ES6 Module Pattern

This is not correct. The introduction of modules in ES6 actually allows us to avoid having to do this to encapsulate our code.

Collapse
 
anewman15 profile image
Abdullah Al Numan

Yes, thanks for pointing out!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay