if i declare variable at top with some value, then using that variable is showing undefined why?
var a = 100;
function test(){
console.log(a);
var a = 1000;
console.log(a);
}
test();
The output is undefined and 1000 why?
if i declare variable at top with some value, then using that variable is showing undefined why?
var a = 100;
function test(){
console.log(a);
var a = 1000;
console.log(a);
}
test();
The output is undefined and 1000 why?
In your function, the local variable masks the global one.
var a = 100;
function test(){
console.log(a);
var a = 1000;
console.log(a);
}
test();
The fact that your var statement is in the function as well as global scope doesn't change anything. The global variable is masked for the whole function.
So, for the whole execution of the function, the global variable will reference the local one, and not the global one.
Outside of that function, though, the global variable will still exist If you want to access the variable inside the function you can use
console.log(window.a);
You might want to read about Hoisting of a javascript variable.
Because of hoisting
, var a = 1000;
is treated as var a;
and a = 1000;
as two different statements. The var a;
statement, which is variable declaration, is moved to the top inside the function due to hoisting.
Now your function is as good as
var a = 100;
function test(){
var a;
console.log(a);
a = 1000;
console.log(a);
}
test();
var a;
statement declares a local variable but is still undefined. So you get undefined
on first console.log(a);
.
To access the global variable learn how to use this
like this.a
.
It's because of the way JavaScript compiles the code.
Firsr it looks for declarations in the scope, then, if inner scopes are present, it looks for their own scope, in this case I'm pretty sure it's like the following:
Global scope will have a variable named
a
and a value of 100 assigned to itThere is a global function declaration named
test
, it needs its own scope, let's go for it2.1. This scope will have a variable named
a
(uninitialized)2.2 There is a call for the
console
object's function namedlog
, it needs to have the variable nameda
, is that variable in this scope? Well, it looks like it is, but does not have a value assigned now so it isundefined
.2.3 NOW I have something to assign the variable, it's 1000, ok, let's continue.
2.4 There is a call for the
console
object's function namedlog
, it needs to have the variable nameda
, is that variable in this scope? Well, it looks like it is, AND its value is 1000console.log(a) => 1000
There is a call for the
test
functionsee 2.1
So, when you call the first console.log(a)
the engine knows there is a local scope's variable named a
, but it is not yet initialized, that's why you get undefined
, then, in the second call, the local scope's a
variable has a value of 1000 assigned to it, local scope is higher in hierarchy than parent scope so the value for the log will be 1000.