Search code examples
google-apps-scriptweb-applicationsglobal-variables

Problems in using global variables in functions


I try to use a global variable in my function, see below. I can use the global variable in my func1 to store a value, for Ex. 77, ok. In func2 I try to use the current value that is stored in the global variable but the result is undefined.

Any advice how to get this working?

doGet() {
    ...
    var buttonValue;
    ...

func1(e,buttonValue) {
    ...
    buttonValue = size;
    throw buttonValue;
    --> buttonValue ok!
    ...
}

func2(e,buttonValue) {
    ...
    throw buttonValue;
    --> buttonValue undefined!
}

Solution

  • You cannot do that. The value of global variables cannot be changed in handler functions etc. Use CacheService to store values that have a global scope

    Here is a code example:

    function func1(){
      CacheService.getPrivateCache().put('var_name', 'var_value');
    }
    
    function func2(){
      var var_value = CacheService.getPrivateCache().get('var_name');
    }