Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Hoisting in Javascript

Tags:

javascript

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.

like image 576
krishna teja Avatar asked Jan 23 '26 09:01

krishna teja


2 Answers

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();
like image 199
lxyyz Avatar answered Jan 26 '26 00:01

lxyyz


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.

like image 24
Quentin Avatar answered Jan 26 '26 00:01

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!