Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Why Is It That Javascript Variables Are Created Undefined Even If They Don't Pass If Statement?"