2

What does this JavaScript code mean? What does this evaluate to and what do the parentheses do?

 /**
 * View Controller
 * @type {Object}
 */

var controller = controller || {};
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
moonfairy
  • 75
  • 3
  • 14
  • 2
    The *braces* `{}` are an empty object literal. The pipes `||` mean "or". If `controller` exists it's `var controller = controller;`, if not it's `var controller = {};`. – jonrsharpe Oct 27 '18 at 20:53
  • This type of thing only makes sense at the top level, by the way – when you don’t know whether `controller` is already declared in the current scope. Usually equivalent to `if (!window.controller) { window.controller = {}; }` in browsers, for example. – Ry- Oct 27 '18 at 20:58
  • Thanks for the explanation and help – moonfairy Oct 28 '18 at 14:22

2 Answers2

1
var controller = controller || {};

So it simply means that if the controller is undefined as default value {} , will be initialised to that particular variable.

here || is simply an OR operator which you might have used in conditional statements.

Abhishek Mani
  • 502
  • 4
  • 12
1

To avoid confusion, I will use different variable names:

var controller = cont || {};

This expression will check the value of cont and if it is undefined, it will assign {} or an empty object to controller. If cont has a value, controller will be assigned that value.

Kushagra Goyal
  • 252
  • 1
  • 8