JS: How to change variable in function (IIFE)

Viewed 576

How to change the s variable using IIFE.n() because now it doesn't work. After I execute IIFE.n() IIFE.s still returns "string"

I've tried with this but I rather use let/const and don't want to pass this variable to global scope I want to keep it in module.

const iife = (() => {
    let s = "string";
    const n = () => {
        s = 1e3;
    };
    return {
        s: s,
        n: n
    };
})()

Currently when I do iife.n() it doesn't change the s variable (when I added return before s = 1e3 it returns 1000 but iife.s still returns "string")

2 Answers

You will need to return the object inside the IIFE.n() function

const iife = (() => {
    let s = "string";
    const n = () => {
        s = 1e3;
        return {
                s: s,
                n: n
            };
    };
    return {
        s: s,
        n: n
    };
})()

iife.n().s returns 1000 iife.s returns "string"

Every time you invoke the iffe it creates its own copy of the variable. In your code when you do iffe.s it doesn't know about the previous invokation of iffe.n(). It will create a new copy of the variable and return that.

It does change s, but you don't have any way to get the updated value, so you can't see that it's changing. Try this and you'll see the updated s:

const iife = (() => {
    let s = "string";
    const n = () => {
        s = 1e3;
    };
    const gets = () => s;
    return {
        s: s,
        n: n,
        gets: gets
    };
})();

iife.n();
console.log(iife.gets());

iife.s is not the same as the s variable. The variable was just used to initialize the property, but they're not linked permanently.

Related