I am trying to solve few coding snippets and found the following snippet little tricky.
var x =100;
function test() {
if(false) {
var x = 200;
}
console.log(x);
}
test();
I expected that it will console 100 but instead it is printing undefined, I really dont understand how the hoisting is happening here as the false block will never execute. Could some one help me know the logic here.
Right, it's caused by JS hoisting. Before ES2015/6 (let/const are block scoped similar to java), the scope of variable in JS are in a functional scope, which means all variables declared in a function will be moved to top of your function
var x =100;
function test() {
if(false) {
var x = 200;
}
console.log(x);
}
test();
will be interpreted as:
var x =100; // global var
function test() {
var x; // local var
if(false) {
x = 200;
}
console.log(x); // climbing up the scope chain resolves to the closest local x, which is undefined.
}
test();
Hosting happens regardless of conditions.
If it didn't, then it couldn't be hoisted until after the if statement was evaluated, in which case it still couldn't be hoisted because it would be too late.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With