2

Why does x = x || 4 or even x=(x||5) generate ReferenceError: x is not defined error, but var x=x || 4 work as expected?

Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173

3 Answers3

2

This is because variable declarations are processed first (hoisting). The MDN page on var explains it well:

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behaviour is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

So the following would also work:

x = x || 4;
var x;
grc
  • 22,885
  • 5
  • 42
  • 63
  • So, why does `x=(x||5)` generate error? Additionally, I don't want use `var` , the variable should be declared globally. – Handsome Nerd Jul 05 '14 at 09:09
  • 1
    Because variable `x` is not known to the parser - and an attempt to access its value throws `ReferenceError`. If you really want to go with global variables, use `window.x = window.x || 4` syntax. – raina77ow Jul 05 '14 at 09:12
  • Note that `x = window.x || 4` will work fine in non-strict mode, but in the strict mode throws an error. – raina77ow Jul 05 '14 at 09:14
  • Yep @raina77ow is spot on. But using globals like that is something to be avoided if possible. – grc Jul 05 '14 at 09:17
  • `x=5` does not generate error so why does `x = x||3` generate error, while in both statements `x` is not declared in advance. Indeed Also, for me `x = x||3` and `x = window.x||3` seems equivalent. – Handsome Nerd Jul 05 '14 at 09:20
  • Strict mode won't allow either. In non-strict mode, you can get away with `x = 5` since you are defining `x`. But the second statement requires `x` to be already defined, since you are using its value. – grc Jul 05 '14 at 09:27
  • And have a look at [this](http://stackoverflow.com/q/10102862/645956) for why `window.x` works. – grc Jul 05 '14 at 09:30
-1

You're attempting to use a variable that hasn't been declared before. This results in a Reference Error.

[edit] so many wrong words.

[exit] @grc got it right.

John C
  • 666
  • 4
  • 8
-1

x = x || 4 means assigning x or 4 in variable x. if x is null 4 is assigned to variable x.

May be you have not declare x variable. that's why you are getting x is not defined

If you try below it work :

var x;
x=x||4;
alert(x);

This will also work :

x=x||4;
var x;
alert(x);
Butani Vijay
  • 4,181
  • 2
  • 29
  • 61