Search code examples
javascriptsyntaxencapsulation

Is it acceptable to encapsulate each js file with an IIFE?


Is it acceptable to encapsulate each js file with an IIFE?

For example, in file somefile.js instead of:

var x = ...
var y = ...
function foo() {...}
...

to make:

(function() {
var x = ...
var y = ...
function foo() {...}
...
}());

And do the same with all of the js files. This will hide the functions and global variables from the users so they won't be able to easily invoke or change them.


Solution

  • Is it acceptable to encapsulate each js file with an IIFE?

    Yes, totally acceptable.

    However it might not be too useful, because you usually want some functions from a js file to be invokable from elsewhere.

    This will hide the functions and global variables from the users so they won't be able to easily invoke or change them.

    No, hiding anything from the users is futile.

    The purpose of IIFEs is to hide the file's local variables from each other, i.e. to separate the js modules.