Search code examples
javascriptgoogle-apps-scriptfunction-call

When passing variable to function I get 'Invalid argument', but when I hard code it works in Apps Script


This is my test function:

var testFolderId = 'di98kjsdf9...';
function testGetFolder(testFolderId){
  folder = DriveApp.getFolderById(testFolderId);
  Logger.log("folders: " + folder);
}

It fails when I do this. The error says: INVALID ARGUMENT

However, if I hardcode the id into the 'DriveApp.getFolderById' function, it works.

Any explanation? This makes no sense to me.


Solution

  • When a function is called directly from the script editor/menu/button click/triggers, the following sequence of actions happens:

    • First, Entire script is loaded and All global statements are executed. This is equivalent to loading a web page with all your script in script tags: <script>...code.gs..</script>

    • The function you called is called. This is like adding callMyFunction() at the bottom of the already loaded script.

    • Except in case of triggers, The function you called is run without passing any arguments. Thus all arguments are undefined

    Caution ⚠️: If the function is called by a trigger, the first parameter passed is usually the event object, while the rest of the parameters are undefined.

    var testFolderId="1dhhddci6";
    //When this function is called by IDE, it called without passing any arguments
    function testGetFolder(testFolderId){//<=same as calling `testGetFolder()` or `testGetFolder(null)`
      //testFolderId is declared in local scope , but is undefined
      folder = DriveApp.getFolderById(testFolderId);//<= testFolderId is undefined 
    

    Workarounds:

    //When this function is called by IDE, it called without passing any arguments
    function testGetFolder(testFolderId="dhhddci6"){//<=same as calling `testGetFolder()`, but `testFolderId` is passed a value. Also same as calling `testGetFolder("dhhddci6")`
      //testFolderId is declared in local scope and is defined(declared and intialized with a value)
      folder = DriveApp.getFolderById(testFolderId);//<= testFolderId is "dhhddci6"
    
    • If global variables are used, Then the arguments should not be declared.
    var testFolderId="1dhhddci6";
    //When this function is called by IDE, it called without passing any arguments
    function testGetFolder(){//<=same as calling `testGetFolder()`
      //testFolderId is NOT declared in local scope, so variable is looked up in global scope(where it is defined)
      folder = DriveApp.getFolderById(testFolderId);//<= testFolderId is "dhhddci6"
    

    Further reading: