Why is the x
variable in the example below returning undefined
rather than 25?
var x = 25;
(function() {
console.log(x);
var x = 10;
})();
Why is the x
variable in the example below returning undefined
rather than 25?
var x = 25;
(function() {
console.log(x);
var x = 10;
})();
This is common problem of hoisting in javascript.The code actually looks like this.The value is assigned after the console.log
.
The second undefined(if run on developer's tool) is because the function is not explicitly returning anything
This is how Javascript actually executes your code due to var
hoisting:
var x = 25;
(function() {
var x;
console.log(x);
x = 10;
})();
It's Self-Invoking Functions that will invoke without calling from specific function or place. and your declared x
inside that function and preparing for running that function make javascript
ignore global variable x
and try to create local x
.if you remove var x = 10;
from the function inside then everything will be OK:
var x = 25;
(function() {
console.log(x);
})();