2

I'm just getting going in javascript and am reading up on the module pattern.

I have been looking at this page: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html and cannot work out what the || {} statements mean.

There are quite a few places where this code is written: (UTIL || {}));

Can anyone explain what these statements mean and what they are doing?

I assume that || means OR - but am not too certain in this context.

Here is the code from the conclusion of the article. The second and the penultimate lines are examples of the code that has me puzzled.

var UTIL = (function (parent, $) {
var my = parent.ajax = parent.ajax || {};

my.get = function (url, params, callback) {
    // ok, so I'm cheating a bit :)
    return $.getJSON(url, params, callback);
};

// etc...

return parent;
}(UTIL || {}, jQuery));
Brian
  • 11,132
  • 7
  • 32
  • 43
Jason White
  • 165
  • 1
  • 1
  • 8

4 Answers4

1

This is used to define a variable if it is not set. You can do this to ensure there is a value set!

for example:

function iHaveParameters(param1, param2) {
   param1 = param1 || {} //empty object
   param2 = param2 || "This should be a string"
}

And of course as noted, it will only invoke the second value when the first variable is null.

And in your case it is actually only setting the variable when it's not set, meaning if you include the script 3000 times, the variable will only still be defined once avoiding CPU. This way you could require the loading of a function for example

Mathijs Segers
  • 5,557
  • 9
  • 44
  • 69
1

As has been said, it's an empty JavaScript object.

What's not so obvious I guess is why you would do that. A common reason is to make your code safe if the object happens to be null or undefined. Consider the example where you are passed an object and want to access an attribute of it:

function myFunc(obj) {
    console.log(obj.name);
}

That's fine, unless obj is undefined, in which case your code will crash.

A safer way is often:

function myFunc(obj) {
    console.log((obj || {}).name);
}

Now if obj is undefined then a new empty object is created instead. Getting the .name of that is safe and will simply return undefined.

This is obviously an over-simplified example, but the technique is widely used to make code shorter and easier to read (less tests and branches than putting if statements everywhere).

randomsock
  • 835
  • 6
  • 8
0

It means: if the object before || is null, use a new empty object {} instead.

Read more about the operator here: Is there a "null coalescing" operator in JavaScript?

Community
  • 1
  • 1
Raphael Müller
  • 951
  • 2
  • 8
  • 20
0

{} is a short way of declaring an empty object, the same way as using [] do declare an empty array.

var my = parent.ajax = parent.ajax || {}; means that if the object parent.ajax exist then set it as the value. If not, set an empty object instead.

Gil
  • 1,398
  • 1
  • 10
  • 16