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")
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.
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.
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.
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With