0

Why is this global variable undefined inside a function if the same global variable is re-declared and defined inside that same function?

var a = 1;
function testscope(){
 console.log(a, 'inside func');
 //var a=2;
};
testscope();
console.log(a, 'outside func');

output:
1 "inside func"
1 "outside func" 

Consider same code where var a = 2; inside function block is uncommented

var a = 1;
function testscope(){
 console.log(a, 'inside func');
 var a=2; 
};
testscope();
console.log(a, 'outside func');

Output
undefined "inside func"
1 "outside func"
Christopher Nuccio
  • 596
  • 1
  • 9
  • 21
Raj Rj
  • 3,497
  • 4
  • 24
  • 34

2 Answers2

5

It's because Javascript is not like Java and variable declaration are always pushed up their block. Your second piece of code is strictly equivalent to:

var a = 1;
function testscope(){
 var a;  // <-- When executed, the declaration goes up here
 console.log(a, 'inside func');
 a=2;  // <-- and assignation stays there
};
testscope();
console.log(a, 'outside func');

Output
undefined "inside func"
1 "outside func"
Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42
-1

because a on the first function refers to the variable a that exists on the function, while a you write after the variable you write. if you want a global variable accessible inside a function that contains the same variable as the global variable you should add this.a. or if you want to access the variable a in the function you have to write the variable before you call it

massam
  • 57
  • 6