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!');
};