Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: How to change variable in function (IIFE)

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

like image 644
Marcinek Avatar asked Jun 08 '19 20:06

Marcinek


People also ask

How do you change a variable in JavaScript?

Changing values In JavaScript, we can simply reassign the new value to the variable. When we change the value of a variable, we do not use var again. We simply use the = to give the variable a new value.

What is function () {} in JS?

In JavaScript, a function allows you to define a block of code, give it a name and then execute it as many times as you want. A JavaScript function can be defined using function keyword.

Is IIFE obsolete?

Quite the contrary is true — the IIFE pattern is not obsolete at all! For this reason, I decided to write this follow-up post to showcase a variety of common use cases for immediately invoked function expressions.

What does IIFE mean in JavaScript?

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.


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.

like image 51
Kamlesh Tajpuri Avatar answered Nov 14 '22 23:11

Kamlesh Tajpuri


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.

like image 38
Barmar Avatar answered Nov 15 '22 01:11

Barmar