0

Check this interactive Google Chrome console log:

test_1 = 'ok'
 > "ok"

test_2 = test_2 || 'ok'
 > ReferenceError: test_2 is not defined

var test_3 = test_3 || 'ok'
 > undefined

test_1
 > "ok"

test_2
 > ReferenceError: test_2 is not defined

test_3
 > "ok"

When I call test_1 = 'ok' I leave out the var constructor, but the browser still understands this. I assume it fills in with the var where I omitted, just like it fills in with semicolons.

But for test_2 = test_2 || 'ok' I get an error. I know test_2 is not defined but it doesn't keep my next example test_3 from working. For some reason the missing var statement becomes a problem.

Can somebody explain to me why the interpreter throws an error there?

3
  • 2
    JavaScript 'hoisting' also look at JavaScript Scoping and Hoisting Commented Jan 23, 2014 at 22:52
  • You can omit var, it implies your variable is global. Commented Jan 23, 2014 at 22:52
  • 2
    I don't understand why you downvote this. Commented Jan 23, 2014 at 22:56

1 Answer 1

2

In short, hoisting.

Take the third example, that "works":

var test_3 = test_3 || 'ok'

What JavaScript actually does is the following:

var test_3;

test_3 = test_3 || 'ok';

Now that test_3 is declared, referring to test_3 simply returns undefined rather than throwing a ReferenceError, so what you're essentially doing is this:

var test_3;

test_3 = undefined || 'ok';

This isn't true with the second example, as test_2 is never declared.

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

1 Comment

"This isn't true with the second example, as test_2 is never defined." You mean it's never declared.

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.