-3

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

Hi I am not so good with javascript. I have searched all over the place and didn't find anything which relates to my query.

I've been seeing a lot of this lately and a bit curious what does this mean?

someValue || {} in javascript?

Thank you much for you help!

Community
  • 1
  • 1
JohnnyQ
  • 4,839
  • 6
  • 47
  • 65
  • All you need to know [over here](http://stackoverflow.com/questions/476436/null-coalescing-operator-for-javascript). – Cᴏʀʏ Jul 19 '12 at 03:06
  • Duh! I tried searching that duplicate question but it didn't appear on the list not even on the Related section see for yourselves! And seriously, isn't one down vote enough? Oh the mentality! Like there are [dumber](http://stackoverflow.com/questions/7525722/smarty-two-or-more-inequality-conditions-in-one-bracket) questions right? – JohnnyQ Jul 30 '12 at 03:14

3 Answers3

4

if someValue falsy, you get {} instead. Its commonly used like so

function(opts) {
   opts = opts || {};
}

so the API consumer can optionally pass in some options. If the caller doesn't pass options, it get initialized so there are no null issues....

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
3

If someValue's value is falsy like:

  • null
  • false
  • empty string
  • 0
  • undefined

then someValue defaults to an object {}.

The || used this way is also known as "default", meaning that if the value to the left of a || is falsy, it "defaults" to the value at the right.

Joseph
  • 117,725
  • 30
  • 181
  • 234
0

To check if somevalue is false or undefined you got {}. For example

function a(p){
   p = p || 'default value';
}
James
  • 13,571
  • 6
  • 61
  • 83