-3

I do not understand the || and {} at the end of the first line here. Please could you explain.

var BubbleShoot = window.BubbleShoot || {};
BubbleShoot.Game = (function($){
var Game = function(){
var curBubble;
Sid
  • 1
  • 1
  • 2
    If the `window.BubbleShoot` exists, then `BubbleShoot` will be set to it. Otherwise it will set `BubbleShoot` to a blank object. – Madness Aug 28 '15 at 16:32
  • 4
    Perhaps a review of [logical operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators) and [object initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) is in order? – Brian Aug 28 '15 at 16:32
  • 4
    I think you're getting down-votes because the title of your post is extremely misleading compared to your actual question. A better title might be _what do || and {} mean in Javascript_ to which there are a number of related or duplicate posts. – ThisClark Aug 28 '15 at 16:34
  • Thanks Brian, I will look into object initializers. Was jumping into this without much Javascript knowledge. – Sid Aug 29 '15 at 10:00
  • OK thanks, for my further posts will refine the title a bit further! – Sid Aug 29 '15 at 10:01

2 Answers2

3

|| is the "or" operator in JavaScript. It returns the value on the left if the value on the left is truthy, otherwise it returns the value on the right.

undefined and null, are both falsey values in JavaScript, so if window.BubbleShoot is one of these, the first line of your code will set the value of BubbleShoot to be {}, which is an empty JavaScript object on which you can set properties like Game as shown in your second line of code.

Robin James Kerrison
  • 1,727
  • 1
  • 15
  • 26
2

The || is the JavaScript operator for 'OR', and the {} is defining a new, empty hash;

Essentially, it's equivalent to the following:

if (window.BubbleShoot != null && window.BubbleShoot != undefined) {
    BubbleShoot = window.BubbleShoot;
} else {
    BubbleShoot = {}; // new, empty hash
}
Chris Disley
  • 1,286
  • 17
  • 30