What does “var FOO = FOO || {}” (assign a variable or an empty object to that variable) mean in Javascript?

前端 未结 7 2180
野性不改
野性不改 2020-11-22 02:07

Looking at an online source code I came across this at the top of several source files.

var FOO = FOO || {};
FOO.Bar = …;

But I have no ide

7条回答
  •  半阙折子戏
    2020-11-22 02:44

    var AEROTWIST = AEROTWIST || {};
    

    Basically this line is saying set the AEROTWIST variable to the value of the AEROTWIST variable, or set it to an empty object.

    The double pipe || is an OR statement, and the second part of the OR is only executed if the first part returns false.

    Therefore, if AEROTWIST already has a value, it will be kept as that value, but if it hasn't been set before, then it will be set as an empty object.

    it's basically the same as saying this:

    if(!AEROTWIST) {var AEROTWIST={};}
    

    Hope that helps.

提交回复
热议问题