Search code examples
google-apps-scriptgoogle-sheetsglobal-variables

Global variable defined in function appears not defined?


I'm writing a script for Google Spreadsheets, I want to have my headers index available globally throughout the script.

According to the theory, I should be able to define global variables from within a function.

function testFunc() {
testVar = 1;       // `testVar` is a Global variable now
}

In my code it looks more or less like this:

function getHeaders() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var headers = data[0]

  headerIdIndex = headers.indexOf("ID")
  headerNameIndex = headers.indexOf("First-Last")
}

However, later on in my code, when I call up the variable headerNameIndex, it appears undefined:

function tellMeNames() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  for (var i = 1; i < data.length; i++) {
    Logger.log("Name: " + data[i][headerNameIndex])
  }
}

Reference Error

So what am I doing wrong? Thanks.


Solution

  • Well, I was going through some relevant SO posts on defining a global variable in Google Apps Script and from this answer it turns out you can not update global variables inside a handler function i.e. Global Variables in GAS are static.

    Now, it depends on your specific use case but I am assuming since you have defined a function getHeaders(), you would want to make a call to it, more than once. If however that's not the case, then you can simply declare and initialize those variables outside the scope of all functions as global variables and read them in any other functions.

    So you might want to try something like this in your case (haven't tested the following code):

     var sheet = SpreadsheetApp.getActiveSheet();
     var data = sheet.getDataRange().getValues();
     var headers = data[0]
    
     headerIdIndex = headers.indexOf("ID")
     headerNameIndex = headers.indexOf("First-Last")
    
     ....
    
     function tellMeNames() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var data = sheet.getDataRange().getValues();
     for (var i = 1; i < data.length; i++) {
      Logger.log("Name: " + data[i][headerNameIndex])
     }
    }
    

    If however you want to store and update global variables in handler functions, you might want to give Script-DB a try. Hope this gets you started in the right direction.