Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript namespaces that use ||

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?
like image 555
Adam Davies Avatar asked Sep 01 '26 23:09

Adam Davies


1 Answers

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
like image 99
Paul Avatar answered Sep 03 '26 12:09

Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!