Anand
Anand

Reputation: 408

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?

Upvotes: 1

Views: 55

Answers (1)

Galunid
Galunid

Reputation: 578

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.

Upvotes: 1

Related Questions