Global scope issue, variable outside function Javascript

I have declared var example at the beginning, outside of function (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    

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

You redeclared it inside of the function using the var keyword. So the variable example inside of the function is not the same variable example that you declared outside of the function. This is called variable shadowing.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.