what does “object || {} ” means in javascript?

后端 未结 3 1044
执笔经年
执笔经年 2021-01-01 07:56

I found below line of code in javascript application.

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

I know there is existing Object parent wh

相关标签:
3条回答
  • 2021-01-01 07:58

    || 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#).

    0 讨论(0)
  • 2021-01-01 08:16

    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

    0 讨论(0)
  • 2021-01-01 08:22

    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={};   
    }
    
    0 讨论(0)
提交回复
热议问题