JS: How to change variable in function (IIFE)
Asked Answered
A

2

5

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")

Adrianaadriane answered 8/6, 2019 at 20:16 Comment(2)
I'm sure it does change s, but there's s the local variable in the closure and also s the property of the returned object. They're two different things.Caro
const iife = (() => { let s = "string"; const n = function() { this.s = 1e3; }; return { s: s, n: n }; })()Adrianaadriane
M
4

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.

Monogram answered 8/6, 2019 at 20:27 Comment(0)
G
3

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.

Gluttonous answered 8/6, 2019 at 20:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.