Home >Web Front-end >JS Tutorial >How Does 'var FOO = FOO || {};' Create and Manage JavaScript Namespaces?
JavaScript Namespace Creation: Understanding "var FOO = FOO || {}"
In the realm of JavaScript, a peculiar pattern frequently encountered at the outset of source files merits investigation: var FOO = FOO || {};. While its purpose may initially seem elusive, the || {} construct plays a crucial role in the establishment of namespaces.
A namespace in JavaScript serves as a named object within which variables and functions can reside, avoiding the undesirable contamination of the global object. By employing this pattern, multiple files sharing the same namespace can interact harmoniously, regardless of the order in which they are loaded.
For instance, consider two files:
var MY_NAMESPACE = MY_NAMESPACE || {}; MY_NAMESPACE.func1 = {};
and
var MY_NAMESPACE = MY_NAMESPACE || {}; MY_NAMESPACE.func2 = {};
Here, the shared namespace ensures that both func1 and func2 are defined correctly within MY_NAMESPACE, irrespective of which file is loaded first. The initial file creates the MY_NAMESPACE object, while subsequent files augment it.
Asynchronous script loading can also benefit from this technique, as seen in the presence of defer attributes on