Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda