-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();
};
})();
3

5 Answers 5

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

if (!a)
  a = b;

or

a = a ? a : b;

Comments

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

is equivalent to this code

if(!(window.myapp)) {
  window.myapp = {};
}

2 Comments

Why the additional parens in !(window.myapp) instead of !window.myapp?
@KitSunde just to be sure that negation applies to the whole expression. Probably we don't need it here.
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 Comment

"if it is not null or false" ...or one of four other falsey values... NaN, undefined, 0, ""
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 = {};
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.