How do I call a function within an IIFE expression

5.3k views Asked by At

Just started out learning js and using the book Javascirpt an Absolute Beginner's Guide. Question is from an example in the book:

var awesomeSauce = (
    function () {     
        var secretCode = "Zorb!";
        function privateCheckCode(code) { 
            if (secretCode == code) { 
                alert("You are awesome!");   
            } else { 
                alert("Try again!");   
            }     
        }
    // the public method we want to return     
        return { 
            checkCode: privateCheckCode     
        }; 
    })();

Question is how do I go about to call this code?

awesomeSauce("Zorg!"); 

doesnt work and neither does

awesomeSauce().privateCheckCode("Zorg!");
4

There are 4 answers

0
Lucero On BEST ANSWER
awesomeSauce.checkCode("Zorg!");

The IIFE returns an object with the checkCode property, that property is the (private) function.

The point of the IIFE is that this scopes the variables and functions within, so that they are not accessible from outside (e.g. privateCheckCode and secretCode exist only inside the IIFE).

Think of the returned object as an "export" of selected values or functionality.

1
Flying Gambit On

Agree with Lucero's answer

1) The IIFE gets executed

2) result of the execution gets assigned to awesomeSauce

So what is the result of execution ?

It is whatever the function returned, below code

return { 
    checkCode: privateCheckCode     
};

In this case, it returns an object with a property named "checkCode" which refers to inner function "privateCheckCode".

In short, it becomes,

awesomeSauce = { 
    checkCode: privateCheckCode     
};

Therefore, you can call your function like this awesomeSauce.checkCode("Zorb!");

0
Anthony Anonde Tonymj On

var awesomeSauce = (
    function () {     
        var secretCode = "Zorb!";
        function privateCheckCode(code) { 
            if (secretCode == code) { 
                alert("You are awesome!");   
            } else { 
                alert("Try again!");   
            }     
        }
    // the public method we want to return
        return ( 
            privateCheckCode     
        ); 
    })();
awesomeSauce('Zorb!')

hey i don't know much but i happened to solve this: return statement return an expression not a code block. just go through the code i guess you will understand

0
Ayush Papnai On

You can call it with console.log(awesomeSauce.checkCode('Zorb!'));

as the iife returns an object which has checkCode key and the privateCheckCode as the value.