Home > Back-end >  Why does console log show variable that is already defined
Why does console log show variable that is already defined

Time:11-25

Curios why this happens

if(typeof TEST === "undefined") {
    var TEST = true;
    console.log(TEST);
}

if i place in console , it returns true if i add again in console , then no console log is shown , which is exactly how I would assume it should work.

When i place in interval , why does it continue to log the variable even though its defined ?

setInterval(function(){
    if(typeof TEST === "undefined") {
        var TEST = true;
        console.log(TEST);
    }
}, 1000);

How can you make it stop showing the log after its defined ? Without clearing the interval

CodePudding user response:

If you put it in the console then var creates a variable in the top level scope. It is undefined, so you assign true to it. If you put it in the console again then it is true from the previous time.

If you put it inside a function, then it is scoped to the function, so every time you run the function you create a new scope and a new var TEST.

Declare the variable in a scope outside the function instead.

CodePudding user response:

In the first case, you're testing the global variable. Once it's defined, it stays defined.

In the second case, the variable is local to the callback function. Every time the function is called, it's a new variable that isn't defined yet.

If you remove the var declaration in the setInterval() version it will assign to the global variable, and it will stay defined.

CodePudding user response:

The simplest solution is probably to use let or const instead of var. If of course you have the possibility.

  • Related