-1

Can somebody please tell me what || this doing here

(function()
{
window.myapp = window.myapp || {};
window.myapp.lang = window.myapp.lang || {};
myapp.lang.Extend = function(subClass, superClass)
{
subClass.prototype = new superClass();
};
})();
  • [Reference - What does this symbol mean in JavaScript?](http://stackoverflow.com/questions/9549780/reference-what-does-this-symbol-mean-in-javascript) –  Mar 07 '12 at 16:04
  • [Logical operator || in javascript, 0 stands for Boolean false?](http://stackoverflow.com/questions/9579262/logical-operator-in-javascript-0-stands-for-boolean-false) – Evan Mulawski Mar 07 '12 at 16:17
  • possible duplicate of [What does this construct (x = x || y) mean?](http://stackoverflow.com/questions/2802055/what-does-this-construct-x-x-y-mean) – Felix Kling Jun 09 '13 at 18:47

5 Answers5

4
window.myapp = window.myapp || {};

It means: create window.myapp as an empty object if it does not already exist.

David Frank
  • 5,696
  • 8
  • 26
  • 42
2

The a = a || b; syntax is equivalent to

if (!a)
  a = b;

or

a = a ? a : b;
Alexander Pavlov
  • 29,538
  • 4
  • 63
  • 88
2
window.myapp = window.myapp || {};

is equivalent to this code

if(!(window.myapp)) {
  window.myapp = {};
}
Sergio Tulentsev
  • 210,238
  • 40
  • 347
  • 343
2

|| is the logical OR operator in Javascript. In this case

window.myapp = window.myapp || {};

assigns window.myapp to itself if it is not null or false, otherwise it assigns an empty object {} to window.myapp.

  • 1
    *"if it is not null or false"* ...or one of four other falsey values... `NaN`, `undefined`, `0`, `""` –  Mar 07 '12 at 16:09
0

|| is a short-circuiting operator

while evaluating x || y , x is evaluated first, if it is true - then there is no need to evaluate y because the operation is anyway going to be true.

in javascript the following values result in 'false' when used as if condition -

0 -0 null "" false undefined NaN

so in your case if window.myapp is 'undefined', that will be evaluated to 'false', and the or operator has to evaluate the next operand {} to complete the operation, which is assigned to window.myapp

so all it is doing is -

if(!(window.myapp)) {
  window.myapp = {};
}
Johnbabu Koppolu
  • 3,146
  • 1
  • 19
  • 33