WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Advanced · question 42 of 100

What is the IIFE (Immediately Invoked Function Expression) pattern, and why is it useful in JavaScript?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

The Immediately Invoked Function Expression (IIFE) pattern is a common JavaScript design pattern that involves wrapping a function expression in parentheses and immediately invoking it. The primary purpose of an IIFE is to create a new scope for the function, allowing you to define private variables and functions that are not accessible from the global scope.

Here’s an example of how to create an IIFE in JavaScript:

    (function() {
        // private variable
        const foo = "bar";
        
        // private function
        function baz() {
            console.log("baz");
        }
        
        // public API
        window.myModule = {
            doSomething() {
                console.log(foo);
                baz();
            }
        };
    })();

In this example, we define an anonymous function expression and immediately invoke it. Within the function, we define a private variable foo and a private function baz. We then create a public API by adding a property to the window object, which exposes a method doSomething that can access the private variable and function.

One of the main advantages of using an IIFE is that it allows you to avoid polluting the global scope with your variables and functions. This can help prevent naming collisions and other issues that can arise when multiple scripts are loaded on a page.

Another advantage of using an IIFE is that it can be used for encapsulation and modularity. By defining private variables and functions within the function, you can create a module or plugin that can be easily reused and maintained.

In summary, the IIFE pattern is a powerful technique for creating private variables and functions in JavaScript and preventing global namespace pollution. It allows you to create modular and reusable code that is easy to maintain and test.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics