r/GoogleAppsScript • u/VAer1 • Aug 16 '25
Question Can let variable be accessed by different script files?
Let us say, I have gsFile1.gs andgsFile2.gs , and but both use variable startRow
Can I declare let startRow; in a separate gs file (outside any functions)? Then just use startRow = .... ; in each gs file?
I mean can let variable be global variable for different script files (within same project)?
1
Upvotes
2
u/WicketTheQuerent Aug 16 '25
Yes, you can declare variables outside of any function. Just be aware that these variables will be loaded before executing any function, including executions using no or limited permissions, like simple triggers.
In some cases, the order of the files will matter, so to keep things simple, declare the variables outside of any function in the first file.
2
u/CompetitiveBee238 Aug 16 '25
yes. all variables decleared outside of any function in any file will be accessible by any function in any file. try it yourself to be sure
1
u/AdministrativeGift15 Aug 17 '25
I think it's perfectly fine to use global variables, especially for the active spreadsheet, active sheet, and active range. You want to add onto the globalThis object with your own object. Using the defineProperty method shown below, these "global variables" will be created on demand and each only gets pulled from the server once.
-1
u/Livid_Spray119 Aug 16 '25
If it is all contained in the same file, yes. But if they are in different files, you can still access them, but only if you import the file with your global constasts or variables as a library.
*** IMPORTANT ***
If it's going to be used as global, it is a good practise to use constant variables, as they won't be able to be changed.
Edit: I mean file as a project. Not different pages in the same file