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

Viewed 21185

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?

8 Answers

For || operations, JS will return the FIRST "truthy" value it finds (reading left-to-right):

var bob = false || undefined ||  0  ||  null || "hi"
//          ^          ^         ^      ^        ^
//          nope       nope      nope   nope     yip
//
// => bob = "hi"

// --------------
// breaking
// --------------
var bob = false || "hi" ||  0  ||  null || undefined
//          ^       ^
//          nope    yip <-- stops here
//                          the rest are ignored
//
// => bob = "hi"

Another trick is to use the && (and) to ensure something exists before accessing it.

For && operations, JS will return the LAST "truthy" value it finds (reading left-to-right).

For example if you're trying to read a property from a multi-level object.

var obj = {
        foo : {
            bar : "hi"
        }
    }

var bob = obj && obj.foo && obj.foo.bar;
//          ^        ^              ^
//          yip      yip            use this
//
// => bob = "hi"

// --------------
// breaking:
// --------------
var bob = obj && obj.foo && obj.foo.sally && obj.foo.bar;
//        ^          ^              ^
//        yip        yip            nope  <-- stops here, 
//                   ^                        and returns the last "yip"
//                   |                        the rest are ignored   |
//                   '-----------------------------------------------'
//
// => bob = obj.foo

Both || and && operations are read left-to-right... so you can have things that might normally throw errors toward the right side, since JS will simply stop reading left-to-right once it detects a truthy/falsey value.

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:

var AEROTWIST;
AEROTWIST = AEROTWIST || {};
Related