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?

Eduardo
  • 22,574
  • 11
  • 76
  • 94
  • 2
    [JavaScript 'hoisting'](http://stackoverflow.com/questions/15311158/javascript-hoisting) also look at [JavaScript Scoping and Hoisting](http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html) – Givi Jan 23 '14 at 22:52
  • You can omit `var`, it implies your variable is global. – elclanrs Jan 23 '14 at 22:52
  • 2
    I don't understand why you downvote this. – bgusach Jan 23 '14 at 22:56

1 Answers1

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.

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63