Raj Rj Raj Rj - 10 months ago 96
Javascript Question

why global variable is undefined inside a function?

why global variable is undefined inside a function if same global variable is redeclared and defined inside that 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"

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download