Skip to content
Advertisement

Why do I get “ReferenceError: test is not defined”

Within my Google Script Project I got two GS files Code.gs and other.gs.

code.gs looks like

var globalSettings = {};
settings();


function settings(){
  other();
  globalSettings.fileName = "file";
  console.log("settings was executed");
}

function primary(){

  console.log("primary was executed");
}

other.gs looks like

function other(){

  console.log("other was executed");
}

when I run the function primary I get

ReferenceError: other is not defined
settings    @ Code.gs:5
(anonymous) @ Code.gs:1

when I move the function other to the file code it works. Could someone explain why? Is there any way the other file could be anywhere in the project?

Advertisement

Answer

Explanation:

Everytime you call a function (in any script in your project), the global variables are automatically executed.

  • This is why if you define var globalSettings = {} as a global decleration, every time you run any function in the project, all the global calls will be executed and therefore globalSettings will be set to an empty object and this is why I don’t use global variables.

  • The global call other and the function decleration other need to be in the same gs script in order to work. Or you could simply call other from within the functions settings or primary and in this way other can stay in a separate script.

For example this would work perfectly fine:

code.gs

// define global variables
var globalSettings = {};

// adjust global variables here as a helper function
function settings(){
  other();
  globalSettings.fileName = "file";
  console.log("settings was executed");
}

// main function to be executed
function primary(){
  settings(); // call settings
  console.log(globalSettings.fileName);
  console.log(globalSettings.date);
  console.log("primary was executed");
}

other.gs

// make additional adjustments to the global variables
function other(){
  globalSettings.date = "today";
  console.log("other was executed");
}

Suggestion:

A better idea to make sure you don’t execute your global declerations, is to use the Class PropertiesService class to store some script or user data and then you can retrieve them either globally or locally (inside the functions) and this will make sure you won’t execute them accidentally upon every execution as it is the case for the global declerations.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement