102

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?

JJJ
  • 31,545
  • 20
  • 84
  • 99
Ricardo Sanchez
  • 3,945
  • 8
  • 44
  • 73
  • Note: The question was edited to reflect that this is a code pattern commonly seen at the top of Javascript source files. – Robert Harvey Jun 22 '11 at 16:42

7 Answers7

154

Your guess as to the intent of || {} is pretty close.

This particular pattern when seen at the top of files is used to create a namespace, i.e. a named object under which functions and variables can be created without unduly polluting the global object.

The reason why it's used is so that if you have two (or more) files:

var MY_NAMESPACE = MY_NAMESPACE || {};
MY_NAMESPACE.func1 = {
}

and

var MY_NAMESPACE = MY_NAMESPACE || {};
MY_NAMESPACE.func2 = {
}

both of which share the same namespace it then doesn't matter in which order the two files are loaded, you still get func1 and func2 correctly defined within the MY_NAMESPACE object correctly.

The first file loaded will create the initial MY_NAMESPACE object, and any subsequently loaded file will augment the object.

Usefully, this also allows asynchronous loading of scripts that share the same namespace which can improve page loading times. If the <script> tags have the defer attribute set you can't know in which order they'll be interpreted, so as described above this fixes that problem too.

Alnitak
  • 313,276
  • 69
  • 379
  • 466
  • 3
    This is exactly the case, there are a couple of js files with the exact same declaration at the beginning, thanks a lot! – Ricardo Sanchez Jun 22 '11 at 12:19
  • 43
    +1 for reading between the lines and explaining the reasons for doing it. It's always good when someone gives the answer that the user actually *wanted* rather than just the one he asked for. :) – Spudley Jun 22 '11 at 12:32
  • 1
    i like to say it's the #ifndef/#define for javascript :) – Darren Kopp Jun 22 '11 at 17:15
  • 2
    `||` is also really useful when you want to provide optional arguments and initialize them to defaults if not provided: `function foo(arg1, optarg1, optarg2) { optarg1 = optarg1 || 'default value 1'; optarg2 = optart2 || 'defalt value 2';}` – crazy2be Jun 22 '11 at 19:24
  • 1
    @crazy2be that doesn't work if the default is truthy, but falsey values are also legal, since the `||` operator can't tell `undefined` from `falsey`. – Alnitak Jun 26 '11 at 14:02
25
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.

Spudley
  • 157,081
  • 38
  • 222
  • 293
  • 1
    actually the scope would be fine in your last example because _JS doesn't have block scope_ – Alnitak Jun 22 '11 at 12:17
  • @Alnitak - meh, you're right; I've been working with closures too much lately and I've forgotten the basics. I'll edit the answer. – Spudley Jun 22 '11 at 12:19
9

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 defined FOO and assigned functionality to it (like a skateboard function). Then you would override it, if you were not checking if it already exists.

Problematic case:

// Definition of co-worker "Bart" in "bart.js"
var FOO = {};

FOO.skateboard = function() {
  alert('I like skateboarding!');
};

// Definition of co-worker "Homer" in "homer.js"
var FOO = {};

FOO.donut = function() {
  alert('I like donuts!');
};

In this case the skateboard function will be gone if you load the JavaScript file homer.js after bart.js in your HTML because Homer defines a new FOO object (and thus overrides the existing one from Bart) so it only knows about the donut 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:

var FOO = FOO || {};

// Definition of co-worker Bart in bart.js
FOO.skateboard = function() {
  alert('I like skateboarding!');
};

// Definition of co-worker Homer in homer.js
var FOO = FOO || {};

FOO.donut = function() {
  alert('I like donuts!');
};

Because Bart and Homer are now checking for the existence of FOO before they define their methods, you can load bart.js and homer.js in any order without overriding each other's methods (if they have different names). So you will always get a FOO object which has the methods skateboard and donut (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:

var FOO = {};

FOO.skateboard = function() {
  alert('I like skateboarding!');
};
Benny Neugebauer
  • 40,817
  • 21
  • 196
  • 177
7

Another common use for || is to set a default value for an undefined function parameter also:

function display(a) {
  a = a || 'default'; // here we set the default value of a to be 'default'
  console.log(a);
}

// we call display without providing a parameter
display(); // this will log 'default'
display('test'); // this will log 'test' to the console

The equivalent in other programming usually is:

function display(a = 'default') {
  // ...
}
alessioalex
  • 57,958
  • 15
  • 152
  • 119
  • You don't need `var` in front of `a`, `a` enters the function's execution context as a *formal parameter*, hence it is already declared. – Fabrício Matté Apr 05 '13 at 22:30
3

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)

sudipto
  • 2,453
  • 1
  • 15
  • 21
1

The || operator takes two values:

a || b

If a is truthy, it will return a. Otherwise, it will return b.

The falsy values are null, undefined, 0, "", NaN and false. The truthy values are everything else.

So if a has not been set (is it undefined) it will return b.

pimvdb
  • 141,012
  • 68
  • 291
  • 345
  • I'm not sure *truthy* and *falsey* should be perpetuated as actual words. Amusing, but not exactly standard. :-) – Orbling Jun 22 '11 at 12:25
  • 4
    @Orbling they're quite commonly used to talk about such values in JS. – Alnitak Jun 22 '11 at 13:18
  • +1 for describe the operator correctly, since it isn't a logical operator. Sometimes it's called "default operator". – Tim Büthe Jun 22 '11 at 13:28
  • @Tim The only difference between `||` in JS (and Perl) and the version in C, C++ and Java is that JS doesn't cast the result to a boolean. It's still a logical operator. – Alnitak Jun 22 '11 at 13:36
  • @Alnitak: Possibly due to the non-professional background of JS developers in the past. – Orbling Jun 22 '11 at 14:21
  • @Orbling Doug Crockford uses those terms. – Alnitak Jun 22 '11 at 14:29
  • @Altinak: His personal website title is also "Douglas Crockford's Wrrrld Wide Web" - I may not be deferring to him as a lexiographic authority anytime soon. ;-) – Orbling Jun 22 '11 at 15:31
  • "Truthy" and "falsy" are also commonly used in the Python community. I find them shorthandy and would not hesitate to use them in discussions of other dynamically-typed languages. – kindall Jun 22 '11 at 15:47
  • @Orbling he may be no lexicographical authority, but I found your previous comment about "non-professional backgrounds" mildly offensive. – Alnitak Jun 22 '11 at 15:57
  • @kindall: Aye, the concept exists in most loosely-typed languages. They are not bad concepts, I just find the words a bit lame. – Orbling Jun 22 '11 at 16:01
  • @Altinak: Find it offensive if you will, it is nevertheless true for the most part. There are expert programmers working in the JS field, yourself included no doubt, but the community has a far larger than average not so. Anyhow, this is getting off topic. – Orbling Jun 22 '11 at 16:03
-1

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 || {};
ZER0
  • 22,173
  • 4
  • 45
  • 51