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

106
Visualizações
Can anyone help me with this weird behaviour of var in javascript?

How does the fruit variable gets overwritten in the if block, but the color variable doesn't gets overwritten in the function block ?

var fruit = "apple";

if(fruit){
    var fruit = "mango";
    console.log(fruit); // mango
}

console.log(fruit); // mango

var color = "blue";

function displayColor(){
    var color = "red";
    console.log(color);
}

displayColor(); // red

console.log(color);  // blue
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The difference is the function creates a local scope. So it creates a variable in the function scope and discards it when the function is done, leaving the GLOBAL color variable untouched.

If statements dont make a scope, so your just redefining the fruit variable in global scope.

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