Home >Web Front-end >JS Tutorial >What does `var FOO = FOO || {};` mean in JavaScript?
What does "var FOO = FOO || {}" (assign a variable or an empty object) mean in JavaScript?
In JavaScript, you may encounter code snippets like:
var FOO = FOO || {}; FOO.Bar = …;
where || {} seems enigmatic. This construction has a specific purpose and is commonly used at the beginning of JavaScript source files.
Understanding the Namespace Pattern
var FOO = FOO || {}; establishes a namespace object named FOO. This pattern is particularly useful when dealing with multiple JavaScript files that need to share and encapsulate functionality without polluting the global object.
How it Works
The || operator acts as a conditional assignment. It first checks if FOO already exists as a variable. If it does, FOO is assigned its existing value. If it doesn't, FOO is assigned the default value of {}, an empty object. This guarantees that FOO will always be an object.
Benefits of Namespace Objects
Employing namespace objects provides several advantages:
Example
Consider two files that share the same namespace:
// File 1 var MY_NAMESPACE = MY_NAMESPACE || {}; MY_NAMESPACE.func1 = { // ... };
// File 2 var MY_NAMESPACE = MY_NAMESPACE || {}; MY_NAMESPACE.func2 = { // ... };
Regardless of the loading order, MY_NAMESPACE.func1 and MY_NAMESPACE.func2 will be accessible within the shared namespace object. This pattern ensures the proper initialization and organization of functionality across multiple JavaScript files.
The above is the detailed content of What does `var FOO = FOO || {};` mean in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!