3

I've seen namespaces in JavaScript defined as:

var AppSpace = AppSpace || {};

and/or

var namespace = {};

Can anyone tell me:

  1. What's the difference?
  2. What's || used for in the first example?
  3. Why, in the first example, is AppSpace used twice?
  4. Which is the preferred syntax?
alex
  • 479,566
  • 201
  • 878
  • 984
Adam Davies
  • 2,742
  • 4
  • 33
  • 52
  • http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/ – Grijesh Chauhan Nov 18 '12 at 11:10
  • Possible dup: http://stackoverflow.com/questions/1378619/javascript-operator – elclanrs Nov 18 '12 at 11:10
  • Not duplication - more to do with how the || operator is used in namespaces. This usage is confusing to Java developers, because in Java you can not perform operations on namespaces in this way. Understanding that the namespace is a first-class object in javascript is a change in mindset and very useful to know. – Adam Davies Nov 18 '12 at 11:39

1 Answers1

9

The || operator is the logical 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:

var AppSpace = AppSpace || {}; // AppSauce doesn't exist (falsy) so this is the same as:
                               // var AppSauce = {};
AppSauce.x = "hi";

var AppSpace = AppSpace || {}; // AppSauce does exist (truthy) so this is the same as:
                               // var AppSauce = AppSauce;
console.log(AppSauce.x); // Outputs "hi"

Versus:

var AppSpace = {};
AppSauce.x = "hi";

var AppSpace = {}; // Overwrites Appsauce
console.log(AppSauce.x); // Outputs undefined
Paul
  • 139,544
  • 27
  • 275
  • 264
  • I'm guessing you were hungry when you wrote the explanation. But thanks, I was thinking the || was probably doing that, yet having trouble chasing down confirmation. – Timberline Aug 08 '13 at 23:19