Skip to content Skip to sidebar Skip to footer

Why This Global Variable Is Undefined Inside A Function?

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(){ conso

Solution 1:

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;
functiontestscope(){
 var a;  // <-- When executed, the declaration goes up hereconsole.log(a, 'inside func');
 a=2;  // <-- and assignation stays there
};
testscope();
console.log(a, 'outside func');

Outputundefined"inside func"1"outside func"

Solution 2:

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

Post a Comment for "Why This Global Variable Is Undefined Inside A Function?"