Scott
Scott

Reputation: 11

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

Upvotes: 0

Views: 1154

Answers (2)

Ismail Ashari
Ismail Ashari

Reputation: 1

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.

Upvotes: 0

Karthikumar
Karthikumar

Reputation: 69

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

Upvotes: 3

Related Questions