Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda