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.
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.
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
©2020 All rights reserved.