15

Im looking at some Backbone.js examples and they have var app = app || {}; at the top of all .js files. I understand the literal meaning of this, but what does it do in reference to everything else?

Edit: you guys are really really fast.

rememberlenny
  • 964
  • 2
  • 10
  • 19

4 Answers4

23

It will define the variable app to an empty object if it is not already defined.

This works because being undefined evaluates to false in Javascript.

If it is defined, it may still be re-defined as an empty object if it has a value which evalutes to false, such as an empty string.

nullability
  • 10,545
  • 3
  • 45
  • 63
  • 3
    Specifically... defines `app` to the empty object if the value of `app` is falsy. – Brad Apr 29 '13 at 17:31
  • inception ! upvoted +1 – Eric Frick Apr 29 '13 at 17:31
  • *"If it is already defined, it will re-define it within the scope of the file."* What does re-define it within the scope of the file mean? The variable is already in scope. –  Apr 29 '13 at 17:38
  • Yes, it will effectively do nothing since it is already in global scope. If this was in a function it would re-define it in local scope. I will clarify. – nullability Apr 29 '13 at 17:42
  • @nullability: That's what I mean. If it's already defined in a function scope, it won't be redefined unless the defined value happened to be a falsey value. Though if we're in a function scope, and it has already been defined, there's no point in using `var` again. –  Apr 29 '13 at 17:43
  • OK, then `var app = app;` would effectively do nothing. – nullability Apr 29 '13 at 17:45
  • 1
    This answer is slightly incorrect. This answer should say "if it is truthy" instead of "if it is not already defined." The following example shows why this answer is incorrect: `var app = false; app = app || {}; /*App now equals {} because app was "falsey" */`. See @recursive's answer for the correct answer. – Steven Wexler Apr 29 '13 at 17:52
17

The || operator in javascript will return the first operand if it is "truthy". If not, it will return the second operand. If app has not been assigned, it will be undefined, which is "falsey". Thus if it is not defined or is otherwise falsey, an empty object {} will be assigned to app.

recursive
  • 83,943
  • 34
  • 151
  • 241
6

This means "define app as an empty object if it's not already defined".

The OR operator in JavaScript does not necessarily yield a boolean. If the left-hand side of the expression yields false then the assignment takes the right-hand side of the expression.

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
2

If app is already defined, the it does nothing. If app is not defined, then it's equivalent to var app = {};

Jakob
  • 24,154
  • 8
  • 46
  • 57