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

2020-02-29 22:50发布

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.

3条回答
孤傲高冷的网名
2楼-- · 2020-02-29 23:31

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

查看更多
叛逆
3楼-- · 2020-02-29 23:38

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={};   
}
查看更多
男人必须洒脱
4楼-- · 2020-02-29 23:38

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

查看更多
登录 后发表回答