Why is IIFE required in the following context?

I am working to emulate the require functionality with a few javascript functions, for example:

// We set up an object that will include all the public modules
// And then a require function which basically just accesses that public module
const modules = {};
function require(moduleName) {
    return modules[moduleName];
modules['math.js'] = function() {
    // hidden implementation details
    let incr = x => ++x;
    return {
        sum(x,y) { return x+y; }

Why is it required to do modules['math.js'] = (function() {...})(); and not just a normal non-invoked function call as above?

>Solution :

modules["match.js"] is only a function. You probably want it to be an object:

modules["math.js"] = { ... };

But then you won’t have private members or functions you can use! Everything will be public. So to solve this we create a closure:

modules["math.js"] = function () {
    let priv = 0;

    return { ... };

Here’s where we are now. To make it a closure AND have modules["math.js"] be a nice object we can use, we immediately call this function:

modules["math.js"] = (function () {
    let priv = 0;

    return { ... };

Now, modules["math.js"] is an object with members and methods we can use, AND it has a private locally scoped variable named priv that can be used only by the module.

This is similar to ES6 modules where you export a select few values bound to identifiers and everything else in the file is private.

Leave a Reply