Why is it that Javascript variables are created undefined even if they don't pass if statement?

Take this for example.

if (b) b = 1;

Reference Error. b is not defined. Makes sense but if I do this...

if (b) var b = 1;

I get undefined in console. and now when I look up what b is it shows as undefined.

If I try to do the same if statement again, it doesn't pass because b is neither true or false, it is undefined, but I guess my question is why does it show up as undefined? Does Javascript go through the if statement regardless if the if statement passes or fails? Thanks.



All vars gets hoisted to the beginning of the scope they are in, initialising their values to undefined. The value is then set when execution reaches the line the var was in originally.

In your second example, b gets initialised as undefined before the if is encountered, due to the var. Think of it as the same as writing the following

var b;
if (b) b = 1;

After this code is executed, b will still be undefined because it will never run into the if block as the initial value is falsy.

As mentioned by pst, this is a language specific feature of JavaScript, so don't expect the same behaviour when writing code in other languages.


JS is not going thru the if statement, but rather it's reading the if part of the statement, and since b is not defined anywhere but within the if statement, you get undefined.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.