See the below example,
function doSomething1(){/*needs ss*/const ss = SpreadsheetApp.openById(/*SPREADSHEET_ID*/);}
function doSomething2(){/*needs ss*/const ss = SpreadsheetApp.openById(/*SPREADSHEET_ID*/);}
function doItAll(){
doSomething1();
doSomething2();
}
Instead of calling Spreadsheet in both functions, this could be simplified using globals as
const ss = SpreadsheetApp.openById(/*SPREADSHEET_ID*/);
function doSomething1(){/*do something with ss*/}
function doSomething2(){/*do something with ss*/}
function doItAll(){
doSomething1();
doSomething2();
}
The problem here can be solved without using global variables by simply passing ss
variable between the functions. But This will get much more complicated with multiple functions requiring access to the ss
variable. And passing ss
is cumbersome. There aren't many ways to avoid a global in Apps script. Modules aren't supported. If you use a IIFE, all functions are hidden from the IDE- making a function call from IDE or anywhere else impossible. Using a global here is much more elegant. But problems arise if I have a simple trigger:
const ss = SpreadsheetApp.openById(/*SPREADSHEET_ID*/);
function doSomething1(){/*do something with ss*/}
function doSomething2(){/*do something with ss*/}
function doItAll(){
doSomething1();
doSomething2();
}
function onOpen(){/*Adds a menu*/}
The menu addition onOpen
will fail because this line is loaded SpreadsheetApp.openById(/*SPREADSHEET_ID*/)
before onOpen
and that line requires permissions/authorizations while onOpen
being a simple trigger doesn't run with any code requiring authorization.
How to declare globals without running into authorization errors?