I've seen namespaces in JavaScript defined as:
var AppSpace = AppSpace || {};
and/or
var namespace = {};
Can anyone tell me:
- What's the difference?
- What's || used for in the first example?
- Why, in the first example, is
AppSpace
used twice? - Which is the preferred syntax?
The
||
operator is thelogical or
which in Javascript returns its left operand if the left operand is truthy, otherwise it returns its right operand. The first syntax is preferable, because you can reuse it it multiple places in your code (say in different files) when you are not sure if the namespace has already been defined or not:Versus: