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 idea what || {}
does.
I know {}
is equal to new Object()
and I think the ||
is for something like "if it already exists use its value else use the new object.
Why would I see this at the top of a source file?
Another common use for || is to set a default value for an undefined function parameter also:
The equivalent in other programming usually is:
Notice that in some version of IE this code won't work as expected. Because the
var
, the variable is redefined and assigned so – if I recall correctly the issue – you'll end up to have always a new object. That should fix the issue:If there is no value in AEROTWIST or it is null or undefined the value assigned to the new AEROTWIST will be {} (a blank object)
The
||
operator takes two values:If a is truthy, it will return
a
. Otherwise, it will returnb
.The falsy values are
null
,undefined
,0
,""
,NaN
andfalse
. The truthy values are everything else.So if
a
has not been set (is itundefined
) it will returnb
.Basically this line is saying set the
AEROTWIST
variable to the value of theAEROTWIST
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:
Hope that helps.
There are two main parts that
var FOO = FOO || {};
covers.#1 Preventing overrides
Imagine you have your code split over multiple files and your co-workers are also working on an Object called
FOO
. Then it could lead to the case that someone already definedFOO
and assigned functionality to it (like askateboard
function). Then you would override it, if you were not checking if it already exists.Problematic case:
In this case the
skateboard
function will be gone if you load the JavaScript filehomer.js
afterbart.js
in your HTML because Homer defines a newFOO
object (and thus overrides the existing one from Bart) so it only knows about thedonut
function.So you need to use
var FOO = FOO || {};
which means "FOO will be assigned to FOO (if it exists already) or a new blank object (if FOO does not exist already).Solution:
Because Bart and Homer are now checking for the existence of
FOO
before they define their methods, you can loadbart.js
andhomer.js
in any order without overriding each other's methods (if they have different names). So you will always get aFOO
object which has the methodsskateboard
anddonut
(Yay!).#2 Defining a new object
If you've read through the first example then you already now what's the purpose of the
|| {}
.Because if there is no existing
FOO
object then the OR-case will become active and creates a new object, so you can assign functions to it. Like: