0

I am new to AppsScript/Javascript and trying to learn what this code passage does. In it, the author writes

var Content = (function (ns) {
  ns.makeContent = function  (e) {
   }  
  return ns;      
}) (Content || {});

and is able to call Content by

function doPost(e) {
  return Content.makeContent (e); 
}

What does it mean to have a variable assignment statement that reads var ... = (...) (...);?

Argyll
  • 8,591
  • 4
  • 25
  • 46
  • 1
    [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) (Immediately Invoked Function Expression) – Reyno Nov 16 '20 at 10:52

2 Answers2

1

A function which looks like:

(function(){
  ...
})()

is what's known as an Immediately Invoked Function Expression. So essentially, it's a function that is run immediately rather than waiting to be called from somewhere else.

Rob Bailey
  • 920
  • 1
  • 8
  • 23
1

This is called immediately invoking function expression. This (Content || {}) means the function to be called with Content object if that exist or pass an empty object.

Note: This code will give error if the variable is declared with const key word

var Content = {
  test: 'Hello'
}

var Content = (function(ns) {
  ns.makeContent = function(e) {}
  return ns;
})(Content || {});

console.log(Content)
brk
  • 48,835
  • 10
  • 56
  • 78
  • Thank you for the explanation! One follow-up please: what does the line `return ns` do? If the function is evaluated anyway and all the function does in this case is to modify an existing object, does it mean that in this case `return ns` is not needed? Or is function return needed as a part of the syntax? – Argyll Nov 16 '20 at 11:01
  • @Argyll `return ns` will return the `Content ` or if `Content` is undefined then it will return a new object – brk Nov 16 '20 at 11:17