Debugging a custom function in Google Apps Script

You can use this hack to see the structure of the arguments being sent into the custom function:

function TEST(input) {
  return (JSON.stringify(input));
}

The results will show up in your sheet like this:

enter image description here


The debugger is probably not lying to you - if you launch that function in the debugger, it will have no parameters passed to it. No worries, though, you just need to make sure that you get values to use for debugging. Take a look at How can I test a trigger function in GAS?, which demonstrates techniques that can be applied for custom functions.

Instead of defining an event to pass to the function, you'll want to provide (or retrieve from your spreadsheet) values for the parameters.

function test_drivingDistance() {
  // Define a set of test values
  var testSet = [[ 'Washington, DC', 'Seattle, WA' ],
                 [ 'Ottawa, ON', 'Orlando, FL'],
                 [ 'Paris, France', 'Dakar, Senegal']];

  // Run multiple tests
  for (var test in testSet) {
    Logger.log('Test ' + test + ' = ' + drivingDistance(testSet[test][0],testSet[test][1]));
  }

  // Get parameters from sheet
  var TestFromSheet = drivingDistance(ss.getRange('A1').getValue(),ss.getRange('A2').getValue());
}

You get the idea. You can still set breakpoints inside your function, or use debugger to pause execution.


Edit - examining arguments

What arguments is the custom function receiving when called from a spreadsheet?

You're limited in what you can do to debug this, since the debugger can't be used to examine your custom function when invoked from Sheets, and security limitations on custom functions block Logging. It might be enough to get an understanding of argument passing in general. While javascript functions may have named parameters, all arguments are passed as an Array-like object, called arguments. This custom function will return an array that reports the arguments received. When called from a spreadsheet, each argument will appear in its own cell, starting at the cell you enter the function into:

function testArguments(  ) {
  var argArray = [];
  for (var arg in arguments) {
    argArray.push("arguments[" + arg + "] = " + JSON.stringify(arguments[arg]))
  }

  return argArray;
}

Screenshot

In javascript, there aren't really types like int or float - just Number. Those parameters will show up without quotes on them, and look like numbers. Dates arrive as Date objects, but when printed this way show up as Date-y strings. Strings have quotes.

A custom function never receives a range as an argument; when you provide a range parameter in the spreadsheet, its contents are collected into a one or two-dimensional array, and the array is the argument.