Chris Cirefice
Chris Cirefice

Reputation: 5805

Function Scope Rules (Google Apps Script Project)

If I have several files in a single Apps Script Project that have a function with the same name, how will the scope be determined?

For example if I have Stuff.gs:

function start() {
  var number = getNumber();
}

function getNumber() {
  return 5;
}

and More.gs:

function getNumber() {
  return 10;
}

And I call start(), how does Google's platform determine which function to call?

I did a test like this, and I didn't get the expected output. The output is 10.0. It seems to me that neither file scope rules are applied, nor static scoping. I created a third file to test further:

Test.gs:

function getNumber() {
  return 15;
}

and now the output is 15.0. I further tested and changed 10 to 20 in More.gs to see if the save timestamp determined the scope, but the output was still 15.0.

So to me it seems that the .gs file creation date determines the scope - the most recent timestamp on the file that contains the function name is used. Am I correct in my assumption or is this just a coincidence and it's determined in some other way?

Also, is this specific to Google's Apps Script, or Javascript in general?

Upvotes: 2

Views: 1180

Answers (2)

Chanuka Asanka
Chanuka Asanka

Reputation: 3014

Using IIFEs with closures to encapsualte

More.gs

const More = (function() {
   function getNumber() {
      return 15;
   }

  return {
    getNumber
  };
})();

Test.gs

const Test = (function() {
   function getNumber() {
      return 15;
   }

  return {
    getNumber
  };
})();

Stuff.gs

function start() {
  var number = getNumber();
  var numberMore = More.getNumber();
  var numberTest = Test.getNumber();
}

In the code above, an IIFE is used to create a closure that encapsulates the count variable and two inner functions: increment and decrement. The count variable is private and can only be accessed by the inner functions.

The IIFE immediately executes, returning an object with references to the inner functions (increment and decrement). These functions have access to the private count variable due to the closure.

Upvotes: 0

Bergi
Bergi

Reputation: 665362

Looks like those declarations are all just in global scope. Subsequent definitions will overwrite the previous ones, so if you are first including Stuff.gs, then More.gs, then Test.gs and are calling your function thereafter it would make sense.

The scoping in JS is static (assuming strict mode without with and local eval), but the global scope may be modified dynamically based on the loaded modules (and their order). This is the behaviour in the most JavaScript environments, some also have an additional file (module) scope.

Upvotes: 3

Related Questions