What Does "Var Foo = Foo || {}" (Assign a Variable or an Empty Object to That Variable) Mean in JavaScript

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

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.

What does variable || {} in javascript?

This code assigns {} to vendorcode if vendorcode is false-y.
Meaning it's undefined, false, 0, null, etc.

If vendorcode is not false-y it'll keep its value.

You can read it out loud as: "vendorcode equals vendorcode OR {}"

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

  • How does the "this" keyword work?

var x = function() vs. function x()  —  Function declaration syntax

  • var functionName = function() {} vs function functionName() {}

(function(){})()  —  IIFE (Immediately Invoked Function Expression)

  • What is the purpose?, How is it called?
  • Why does (function(){…})(); work but function(){…}(); doesn't?
  • (function(){…})(); vs (function(){…}());
  • shorter alternatives:
    • !function(){…}(); - What does the exclamation mark do before the function?
    • +function(){…}(); - JavaScript plus sign in front of function expression
    • !function(){ }() vs (function(){ })(), ! vs leading semicolon
  • (function(window, undefined){…}(window));

someFunction()()  —  Functions which return other functions

  • Two sets of parentheses after function call

=>  —  Equal sign, greater than: arrow function expression syntax

  • What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

|>  —  Pipe, greater than: Pipeline operator

  • What does the "|>" operator do in JavaScript?

function*, yield, yield*  —  Star after function or yield: generator functions

  • What is "function*" in JavaScript?
  • What's the yield keyword in JavaScript?
  • Delegated yield (yield star, yield *) in generator functions

[], Array()  —  Square brackets: array notation

  • What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
  • What is array literal notation in javascript and when should you use it?

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value}  —  Curly brackets: object literal syntax (not to be confused with blocks)

  • What do curly braces in JavaScript mean?
  • Javascript object literal: what exactly is {a, b, c}?
  • What do square brackets around a property name in an object literal mean?
  • How does this object method definition work without the "function" keyword? (ES2015 Method definitions)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}`  —  Backticks, dollar sign with curly brackets: template literals

  • What does this `…${…}…` code from the node docs mean?
  • Usage of the backtick character (`) in JavaScript?
  • What is the purpose of template literals (backticks) following a function in ES6?

//  —  Slashes: regular expression literals

  • Meaning of javascript text between two slashes

$  —  Dollar sign in regex replace patterns: $$, $&, $`, $', $n

  • JavaScript replace() method dollar signs

()  —  Parentheses: grouping operator

  • MDN: Grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"]  —  Square brackets or dot: property accessors

  • JavaScript property access: dot notation vs. brackets?

?., ?.[], ?.()  —  Question mark, dot: optional chaining operator

  • Question mark after parameter
  • Null-safe property access (and conditional assignment) in ES6/2015
  • Optional Chaining in JavaScript
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

::  —  Double colon: bind operator

  • JavaScript double colon (bind operator)

new operator

  • What is the 'new' keyword in JavaScript?
  • What is "new.target"?

...iter  —  Three dots: spread syntax; rest parameters

  • (...rest) => {}  —  What is the meaning of “…args” (three dots) in a function definition?
  • fn(...args)  —  What is the meaning of “foo(…arg)” (three dots in a function call)?
  • [...iter]  —  javascript es6 array feature […data, 0] “spread operator”
  • {...props}  —  Javascript Property with three dots (…), What does the '…rest' stand for in this object destructuring?


Increment and decrement

++, --  —  Double plus or minus: pre- / post-increment / -decrement operators

  • ++someVariable vs someVariable++ in Javascript


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

  • What is the purpose of the delete operator in Javascript?

void operator

  • What does `void 0` mean?

+, -  —  Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

  • What does = +_ mean in JavaScript, Single plus operator in javascript
  • What's the significant use of unary plus and minus operators?
  • Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
  • Why does JavaScript handle the plus and minus operators between strings and numbers differently?

|, &, ^, ~  —  Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

  • What do these JavaScript bitwise operators do?
  • How to: The ~ operator?
  • Is there a & logical operator in Javascript
  • What does the "|" (single pipe) do in JavaScript?
  • What does the operator |= do in JavaScript?
  • What does the ^ (caret) symbol do in JavaScript?
  • Using bitwise OR 0 to floor a number, How does x|0 floor the number in JavaScript?
  • Why does ~1 equal -2?
  • What does ~~ ("double tilde") do in Javascript?
  • How does !!~ (not not tilde/bang bang tilde) alter the result of a 'contains/included' Array method call? (also here and here)

%  —  Percent sign: remainder operator

  • What does % do in JavaScript?

&&, ||, !  —  Double ampersand, double pipe, exclamation point: logical operators

  • Logical operators in JavaScript — how do you use them?
  • Logical operator || in javascript, 0 stands for Boolean false?
  • What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?, JavaScript OR (||) variable assignment explanation, What does the construct x = x || y mean?
  • Javascript AND operator within assignment
  • What is "x && foo()"? (also here and here)
  • What is the !! (not not) operator in JavaScript?
  • What is an exclamation point in JavaScript?

??  —  Double question mark: nullish-coalescing operator

  • How is the nullish coalescing operator (??) different from the logical OR operator (||) in ECMAScript?
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

**  —  Double star: power operator (exponentiation)

  • x ** 2 is equivalent to Math.pow(x, 2)
  • Is the double asterisk ** a valid JavaScript operator?
  • MDN documentation


Equality operators

==, ===  —  Equal signs: equality operators

  • Which equals operator (== vs ===) should be used in JavaScript comparisons?
  • How does JS type coercion work?
  • In Javascript, <int-value> == "<int-value>" evaluates to true. Why is it so?
  • [] == ![] evaluates to true
  • Why does "undefined equals false" return false?
  • Why does !new Boolean(false) equals false in JavaScript?
  • Javascript 0 == '0'. Explain this example
  • Why false == "false" is false?

!=, !==  —  Exclamation point and equal signs: inequality operators

  • != vs. !==
  • What is the difference between != and !== operators in JavaScript?


Bit shift operators

<<, >>, >>>  —  Two or three angle brackets: bit shift operators

  • What do these JavaScript bitwise operators do?
  • Double more-than symbol in JavaScript
  • What is the JavaScript >>> operator and how do you use it?


Conditional operator

?:…  —  Question mark and colon: conditional (ternary) operator

  • Question mark and colon in JavaScript
  • Operator precedence with Javascript Ternary operator
  • How do you use the ? : (conditional) operator in JavaScript?


Assignment operators

=  —  Equal sign: assignment operator

  • What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)

This symbol is also used for default parameters or default values in a destructuring assignment:

  • what does (state = {}) => state means
  • What does ({"key": "value"} = {}) syntax mean inside a JavaScript function

%=  —  Percent equals: remainder assignment

  • Having Confusion with Modulo operator

+=  —  Plus equals: addition assignment operator

  • How does += (plus equal) work?

&&=, ||=, ??=  —  Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

  • What purpose do &&=, ||= and ??= serve?
  • Replace a value if null or undefined in JavaScript
  • Set a variable if undefined
  • Ruby’s ||= (or equals) in JavaScript?
  • Original proposal
  • Specification

<<=, >>=, >>>=, &=, ^=, |= — Double less than, double greater than, triple greater than, ampersand, caret, or pipe followed by equal sign: bitwise assignments

  • What do these JavaScript bitwise operators do?

Destructuring

  • of function parameters: Where can I get info on the object parameter syntax for JavaScript functions?
  • of arrays: Multiple assignment in javascript? What does [a,b,c] = [1, 2, 3]; mean?
  • of objects/imports: Javascript object bracket notation ({ Navigation } =) on left side of assign


Comma operator

,  —  Comma operator (not to be confused with the comma used in variable declarations)

  • What does a comma do in JavaScript expressions?
  • Comma operator returns first value instead of second in argument list?
  • When is the comma operator useful?


Control flow

{}  — Curly brackets: blocks (not to be confused with object literal syntax)

  • JavaScript curly braces with no function or json

Declarations

var, let, const  —  Declaring variables

  • What's the difference between using "let" and "var"?
  • Are there constants in JavaScript?
  • What is the temporal dead zone?
  • var a, b;  —  Comma used in variable declarations (not to be confused with the comma operator): JavaScript variable definition: Commas vs. Semicolons


Label

label:  —  Colon: labels

  • What does the JavaScript syntax foo: mean?
  • What does ':' (colon) do in JavaScript?


Other

123n  —  n after integer: BigInt

  • What does character 'n' after numeric literal mean in JavaScript?

#  —  Hash (number sign): Private methods or private fields

  • What does the # symbol do in JavaScript?

_  —  Underscore: separator in numeric literals

  • Javascript numeric separators?
  • Is there a Javascript equivalent to the Ruby syntax using underscores (e.g. 10_000 = 10000) to make larger integers human readable?

What it exactly means in Javascript (assigning variable)

The || is effectively working like a SQL COALESCE statement.

var x = y || z;

means:

if y evaluates to a "truthy" value, assign y to x.

if y evaluates to a "falsy" value, assign z to x.

See http://11heavens.com/falsy-and-truthy-in-javascript for more detail on "truthy/falsy" (or just google it).

What does this mean in JavaScript: var controller = controller || {};

To avoid confusion, I will use different variable names:

var controller = cont || {};

This expression will check the value of cont and if it is undefined, it will assign {} or an empty object to controller. If cont has a value, controller will be assigned that value.

What is the x = x || {} technique in JavaScript - and how does it affect this IIFE?

Pattern
(function (foo) {
...code...
foo.bar = baz;
...more code...
}(window.FOO = window.FOO || {});

There is no formal name for the pattern you describe, because it's three separate patterns combined. Each pattern goes by multiple names, but for this post I will use the following terminology:

  • closure
  • alias
  • namespace extension

Closure

The base of the entire pattern is the closure. It is simply a function that is used to scope variables and functions such that they don't pollute the global namespace:

No closure
//these declare window.foo and window.bar respectively
//as such, they pollute the global namespace
var foo;
function bar() {}
Closure, in this case, an Immediately Invoked Functional Expression (IIFE)
(function () {
//these declare foo and bar within the function
//but they are not accessible outside the function
var foo;
function bar() {}
}());

The advantage of keeping variables within a closure is that you won't have to worry about someone overwriting the variables that you're using. This is especially important for temporary variables such as i or j that are used often.

Alias

The second important part of this pattern is aliasing. Aliasing allows a variable to be defined and used within a closure without needing to worry about what global namespace it resides in.

Without Aliasing
(function () {
...
foo = window.SomeFunction(bar, baz);
...
}());
With Aliasing
(function (sf) { //local name
...
foo = sf(bar, baz);
...
}(window.SomeFunction)); //global namespace

This is especially important as it means that the global namespace can be changed across a large JavaScript file by changing the name in a single location. This is A Good Thing™. Additionally, minifiers can shorten the internal alias to a single letter variable name such as a, making for significant byte savings on minification.

Namespace Extension

The namespace extension pattern relies on the coalescing behavior of the or operator (||). In many languages, && and || return either true or false, but in JavaScript, && returns the first falsey value (false, 0, '', null, undefined), and || returns the first truthy value (anything that's not falsey). For both operators, if the respective type is not found, the last argument is returned. This makes the || operator a convenient way of defining a new namespace only if it doesn't already exist.

Without namespace extension
if (typeof window.Foo === 'undefined') {
window.foo = {};
}
With namespace extension
window.foo = window.foo || {};

This is useful because it allows a namespace to be extended with additional properties and methods without having to worry about which order the properties and methods were defined in.

In this first example, FileA would need to be executed before FileB:

FileA.js
window.foo = {};
window.foo.bar = 'baz';
FileB.js
window.foo.fizz = 'buzz';

In this second example, File1 and File2 could be executed in any order:

File1.js
window.foo = window.foo || {};
window.foo.bar = 'baz';
File2.js
window.foo = window.foo || {};
window.foo.fizz = 'buzz';

All together now

Using each pattern together creates a very powerful modular script:

//use foo internally so that you don't have to worry about
//what the global namespace is called
(function (foo) {
//declare variables internally that you want to keep local to the script
var i,
len,
internal,
qux;
//declare functions/properties on the alias when you want to expose them
foo.bar = function () {...};
//extend the global namespace so that existing extensions are persistent
}(window.FOO = window.FOO || {}));


Related Topics



Leave a reply



Submit