3

I found below line of code in javascript application.

var auth = parent.auth = parent.auth || {};

I know there is existing Object parent which is extended with auth Object but i don't understand what is parent.auth || {} doing here.

Sandeep vashisth
  • 1,040
  • 7
  • 20
  • 40
  • 1
    `var newVar = false || null || true` will assign `true` to `newVar`. the logical or operator is used to prevent _falsy_ values from being assigned. If `parent.auth` is falsy, or doesn't exist, then a new object literal is assigned – Elias Van Ootegem Jun 18 '14 at 09:41
  • Related: [What does the construct x = x || y mean?](http://stackoverflow.com/questions/2802055/what-does-the-construct-x-x-y-mean/) – Michał Perłakowski Jan 11 '16 at 01:59

3 Answers3

6

parent.auth || {} means if parent.auth is undefined, null or false in boolean case then new empty object will be initialized and assigned.

or you can understand it like:

var auth;
if(parent.auth){       
    auth=parent.auth;   
} else {
    auth={};   
}
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • 1
    @sp00m the second approach explains the same. CLEARLY!! – Mr_Green Jun 18 '14 at 09:46
  • @Mr_Green What to you mean? I just wanted to add that 0, "" or NaN will be evaluated to false (i.e. falsy) as well as null, false or undefined. – sp00m Jun 18 '14 at 09:49
  • @sp00m the caps letter in my above comment means it is very clear that this six types falsies will be evaluated to false but not as I am shouting at you. :) – Mr_Green Jun 18 '14 at 09:55
3

it means if the value of parent.auth is falsy(false, 0, null, undefied etc) then assign the value {}(empty object) to the variable auth

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • but why parent.auth is assigned two times – Sandeep vashisth Jun 18 '14 at 09:47
  • @Sandeepvashisth it is because the `parent.auth`'s value itself is updated with the empty object if it is a falsy value... so once the statement is executed `parent.auth` will have a non falsy value – Arun P Johny Jun 18 '14 at 09:49
  • @Sandeepvashisth Maybe reading about [operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) helps to understand this better? – Teemu Jun 18 '14 at 09:53
0

|| is or, the code then returns an empty object, if parent.auth is undefined.

Like checking for null, then creating a new object if null (from java/c#).

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311