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

161
Visualizações
Global scope, variable outside function Javascript

I have declared var example at the beginning (it should be in global scope, or?!). Why it is undefined after calling the function?

var example;
  
  function test(){
    var x = 2;
    var y = 5;
    var example = x + y;
    console.log(example);  // 7: works OK after calling the function    
  };

  test();
  console.log(example); // undefined ?!

Edit: Hello, Thanks for your answers, I´ve found an article about this - Variable Shadowing

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The reason is you have initialized the variable twice. First Initialization outside the function block which is globally available, Second within the function block which is specifically available to the function block.

Your Second Initialization will override the first within the function. After execution of the function, the second example variable will no longer be available and it will be referencing the globally declared first example variable.

var example;
  
  function test(){
    var x = 2;
    var y = 5;
    example = x + y;
    console.log(example);  //Prints the value     
  };

  test();
  console.log(example); // Prints the value
about 4 years ago · Juan Pablo Isaza Relatório

0

the first console.log(example) is running the example inside the function block, so it will print the value of the command you gave.

the second console.log(example) is running the example you declare in first line which is doesn't has value, so it will print undefined.

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