Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
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 {
        incr, 
        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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!