27

Possible Duplicate:
What does “options = options || {}” mean in Javascript?

I have seen this in JS:

item = item || {};

I'm guessing it's some variation of a ternary operator but what does is actually do?

Community
  • 1
  • 1
benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • 7
    Are we getting some Javascript snobbs in the house tonight downvoting or just general silly people!? – benhowdle89 Apr 27 '12 at 22:48
  • 1
    @Martin. and what would you suggest I could have searched to receive this answer... – benhowdle89 Apr 27 '12 at 22:49
  • good question. I have been searching for a while and finally [got it](http://stackoverflow.com/questions/9579262/logical-operator-in-javascript-0-stands-for-boolean-false). But to be honest, it isn't as easy as I thought. Reverting all my downvotes – Martin. Apr 27 '12 at 22:58
  • 1
    @Martin. Thank you. As a self taught developer, believe me, if I could have Googled it...I would have. – benhowdle89 Apr 27 '12 at 23:00
  • @ben yep, I've had a discussion about this on meta (now lost). Yep, it is really hard to search for such operators. – Martin. Apr 27 '12 at 23:04
  • @Martin, may be it's been answered million times but these answers are not wrong in context and it's wrong to down vote a right answer. Well, you mentioned cwolves that why he didn't voted it to close the answer but my question is why you didn't voted to close the question ? – The Alpha Apr 27 '12 at 23:04
  • @Martin. I understand but none deserve a down vote for a poor answer unless it's wrong, you may don't up vote it and could have made a comment. – The Alpha Apr 27 '12 at 23:08
  • But finally you removed your down votes, that's a good thing. :-) – The Alpha Apr 27 '12 at 23:11
  • 1
    @SheikhHeera two of them are wrong, they words like `if item exist` or `if item is not defined`, this is wrong since they don't cover all possibilities. But he still did wrong because he dv because other reasons – ajax333221 Apr 27 '12 at 23:36
  • After all, I got downvoted into oblivion - just as I expected :) – Martin. Apr 27 '12 at 23:50
  • @Martin. I try not to get too worked up over imaginary internet points. – arkon Aug 06 '16 at 07:05

4 Answers4

38
(expr1 || expr2)

"Returns expr1 if it can be converted to true; otherwise, returns expr2."

source

So when expr1 is (or evaluates to) one of these 0,"",false,null,undefined,NaN, then expr2 is returned, otherwise expr1 is returned

ajax333221
  • 11,436
  • 16
  • 61
  • 95
12

It's called redundancy, but in this case it's a good thing. Basically, if item is not defined (or otherwise falsy (false, 0, ""...), then we give it a default value.

Most common example is in events:

evt = evt || window.event;
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
8

If item exists, set item to item, or set it to {}

Martin.
  • 10,494
  • 3
  • 42
  • 68
Dhaivat Pandya
  • 6,499
  • 4
  • 29
  • 43
2

It equates to:

if( !item ){ item = {}; }
Martin.
  • 10,494
  • 3
  • 42
  • 68