0

I am reading a book on Google Scripting, and don't understand the syntax or what the last line accomplishes after the function closes (between here). Am I to read that as: Objectname or empty object brackets? What might this possibly mean?

var Objectname = (function (parameter) {

  //additional scripting omitted here

  return parameter;

}) (Objectname || {});  //I don't understand the purpose of this final statement: (Objectname || {})
Mark1010
  • 21
  • 1
  • 5
  • 1
    Lots of duplicates, e.g. http://stackoverflow.com/q/2802055/218196 . Please use the search! – Felix Kling Mar 07 '16 at 19:06
  • I guess that's because people mostly use google for searching anywhere instead of appropriate search engine and since google doesn't accept special punctuation questions like this one arise. I could swear I've seen that question asked 2 days ago. –  Mar 07 '16 at 19:12
  • Stackoverflow's search engine also ignores "special symbols"? Edit, cannot post [link](http://stackoverflow.com/search?tab=newest&q=%22||%20{}%22) –  Mar 07 '16 at 19:14
  • @vove: Stack Overflow's used to be better at this. Either way, because of that it often helps to search with the name of the operator or a description of how it looks like: [`[javascript] double pipe`](https://stackoverflow.com/search?q=%5Bjavascript%5D+double+pipe), [`[javascript] boolean "OR" operator`](https://stackoverflow.com/search?q=%5Bjavascript%5D+boolean+%22OR%22+operator) – Felix Kling Mar 07 '16 at 20:04

2 Answers2

0

The () calls the function which precedes it.

Objectname || {} is the argument list.

|| is an OR operator. If the left hand side is true, it evaluates as the left hand side, otherwise it evaluates as the right hand side.


If you remove all the shorthand from this you end up something roughly (it creates an additional global variable) along the lines of:

function initialise_objectname(parameter) {
    // ...
    return parameter;
}
var Objectname;
if (Objectname) {
    Objectname = initialise_objectname(Objectname);
} else {
    Objectname = initialise_objectname({});
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Here's an example:

var hello = false;
var test = hello || 123;

//test == 123 because hello == false

Example 2:

var hello = true;
var test = hello || 123;

//test == true because hello == true

Makes sense? If the left hand side is true, it will set it to that, otherwise it will pick the other side.

MortenMoulder
  • 6,138
  • 11
  • 60
  • 116