If I remove "var", the browser(Chrome) complains : "someVar is not defined"
var someVar = someVar || {};
From what I know, it should complain only if I am not initializing the variable.
If I remove "var", the browser(Chrome) complains : "someVar is not defined"
var someVar = someVar || {};
From what I know, it should complain only if I am not initializing the variable.
From what I know, it should complain only if I am not initializing the variable.
But you are trying to read an undeclared variable. Given
someVar = someVar || {};
it first evaluates someVar || {}
and tries to get the value of someVar
in the process. Since someVar
doesn't exist (yet), you get a reference error.
Here is an example that does not throw an error:
someVar = true || someVar;
Because ||
does shirt-circuiting evaluation, the second operand is never evaluated and thus no error is thrown.
Why does it work with var
then?
You might think that using the var
keyword wouldn't make a difference since someVar || {}
is still evaluated first. However, due to hoisting, the statement
var someVar = someVar || {};
is actually evaluated as
var someVar;
someVar = someVar || {};
So at the moment someVar
is read, it is already declared.