I have a variable called isHome
set to false
initially. Then I have a couple of functions to comeHome
and greetMother
that should execute depending on whether isHome
is true or false.
After comeHome
is called (because isHome = false
) it sets isHome
to true. But how come the greetMother()
isn't being called afterwards?
It would be nice to get an in-depth explanation for why I can't (programmatically) greet my mother :/
(Note: I don't have much exp with JS, this is my first SO question, and apologies in advance if I created a duplicate Q)
The code:
let isHome = false;
const comeHome = () => {
isHome = true;
console.log("Going home now");
};
const greetMother = () => {
console.log("Hi Mom!");
};
if (isHome === false) {
setTimeout(() => {
comeHome();
}, 2000);
}
// console.log(isHome) here returns false
if (isHome === true) {
greetMother();
}
The output, and expected outcome
"Going home now"
I console-logged isHome on that line, and it still returns false even though comHome() sets it to true. My assumption is that JS can update global variables from inside functions without needing to use return
, so this problem is unexpected for me.
What I tried:
I tried swapping the conditionals (true first, false second)
Tried using if..else if.. statements
Tried wrapping the whole code inside a function, then running that one function
Tried the object oriented approach, but same result.
class AppObj {
constructor() {
this.isHome = false;
}
comeHome() {
this.isHome = true;
console.log("Going home now");
}
greetMother() {
console.log("Hi Mom!");
}
run() {
if (this.isHome === false) {
setTimeout(() => {
this.comeHome();
}, 2000);
}
if (this.isHome === true) {
this.greetMother();
}
}
}
const appObj = new AppObj();
appObj.run()