Search code examples
javascriptiife

Understanding the IIFE Scoping in Javascript


I came across something similar. Can someone help me understand why is this behavior happening. Is it something to do with scoping for IIFE?

const iife = (() => {
    
    let myValue = "Previous";
    const getValue = () => myValue;
    const setValue = (val) => {myValue = val}

return {
    myValue:myValue,
    getValue:getValue,
    setValue:setValue
}

})()

//console outputs
iife //{myValue:"Previous", getValue:f, setValue:f}
iife.setValue("New");
iife.getValue() //"New"
iife // {myValue:"Previous", getValue:f,setValue:f}

How is it possible to get the iife.getValue() = "New" value even though it is not changed for myValue variable?


Solution

  • setValue changes the value inside iife function. When you return the new object, it creates the copy of the myValue variable, so iife.myValue !== myValue. You can see it if you modify the code as follows:

    const iife = (() => {
        
        let myValue = "Previous";
        const getValue = () => myValue;
        const setValue = (val) => {myValue = val}
    
        setInterval(() => console.log(myValue), 100)
    
    return {
        myValue:myValue,
        getValue:getValue,
        setValue:setValue
    }
    
    })()
    
    //console outputs
    iife //{myValue:"Previous", getValue:f, setValue:f}
    iife.setValue("New");
    iife.getValue() //"New"
    iife // {myValue:"Previous", getValue:f,setValue:f}
    

    It will print whatever you put in iife.setValue.