17

I saw this in a Javascript example

my_var = my_var || 69

I assume it means to check if my_var exists, if not set my_var to 69. Is this the case? Is there any documentation on this, it is very hard to represent as a google/SO search, could somebody point me in the direction of docs or duplicate QA?

(The example didn't use 69, that's just me being crass)

Dom Vinyard
  • 2,038
  • 1
  • 23
  • 36
  • You might find those question interesting: http://stackoverflow.com/q/894860/1169798 and http://stackoverflow.com/q/894860/1169798 – Sirko May 10 '13 at 09:35
  • Beware that this is a bad idea since it doesn't work for falsey values of my_var, they will get overwritten. – flup May 10 '13 at 09:37
  • It doesn't check if `my_var` exists. If `my_var` does not exist, you get `ReferenceError: my_var is not defined`. – Álvaro González May 10 '13 at 09:37

3 Answers3

12

Easy enough to try in the JS console.

var my_var
my_var = my_var || 69
//69

var my_var = 5
my_var = my_var || 69
//5

You are setting the variable only if it is currently carrying a falsy value.

Falsy values in JS are:

  1. false
  2. null
  3. undefined
  4. The empty string ''
  5. The number 0
  6. The number NaN
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • 2
    +1 for the "falsy". People often use this to set a default value if my_var wasn't already set, but it's important to keep in mind that it won't work as expected as soon as 0 or NaN are acceptable values for this variable. – Shautieh May 10 '13 at 09:46
0

It's called "default" most of the time. The value "defaults" to the value after ||. The operation is loose comparison, like what you do with the if statements using ==.

Anything not falsy like:

  • false
  • empty string ('')
  • null
  • undefined
  • 0
  • NaN

is considered true. If the first value isn't any of these, then it's the one assigned. If it is, the value on the right is assigned.

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

The || or operator has two operands (left and right). It checks whether the value to the left is truthy and if so assigns that to the variable otherwise assigns the right hand value to the variable.

var my_var = false;
my_var = my_var || true;
//true
Mark Walters
  • 12,060
  • 6
  • 33
  • 48