0

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.

13
  • 2
    Without the var... you aren't initializing it. So it complains. Commented Dec 10, 2014 at 15:49
  • But if I say "someVar = 5;", I do not need a "var". Is it something to do with the conditional nature of initialization? Commented Dec 10, 2014 at 15:51
  • It's a warning, not an error. Correct? Commented Dec 10, 2014 at 15:51
  • 1
    a = 5 does not try to read a. a = a || 5 tries to read a, so if it doesn't exist, an error is thrown. Commented Dec 10, 2014 at 15:56
  • 1
    @Paddy: It explains the difference between declared and undeclared variables. Accessing an undeclared variable will throw a reference error. Commented Dec 10, 2014 at 15:58

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So, I got confused with the hoisting thing, and this link discuses the concept in more mundane manner : adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.