Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
Why does console log show variable that is already defined

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!