In Apps Script, How to include optional arguments in custom functions
Asked Answered
I

2

28

I want to write a custom function which has some mandatory arguments but can also accept a few optional arguments. I couldn't find any documentation on this. Does anyone know? Is it similar to Javascript?

Ianteen answered 1/6, 2012 at 2:45 Comment(0)
V
29

Custom functions don't have a concept of required and optional fields, but you can emulate that behavior using logic like this:

function foo(arg1, opt_arg2) {
  if (arg1 == null) {
    throw 'arg1 required';
  }
  return 'foo';
}

It's convention to use the prefix "opt_" for optional parameters, but it's not required.

Valentinavalentine answered 4/6, 2012 at 14:12 Comment(1)
better coding convention: if( null == arg1 ) as this can't be mistaken for an assignment when you accidentally leave off one =. if( null = arg1 ) will throw an error which you immediately fix. if( arg1 = null ) will give you confusing results until you find the missing =Tamatave
T
3

Yes, it is JavaScript (with a limited support for JsDoc too), so you can have an optional parameter with a default value:

/**
 * This is myFunction.
 * @param {number} arg1 - Some number.
 * @param {string} arg2 - Some string.
 * @param {number} arg3 - [OPTIONAL] Additional numbers or ranges to add to value1.
 * @customFunction
**/
function myFunction(arg1, arg2, arg3=false) {
  return arg3;
}

And then you could call it in your spreadsheet using either:

=myFunction(1, "somestring", true)

Or without the optional parameter:

=myFunction(1, "somestring")

Since JavaScript dynamically handles the parameter list.

Thibeault answered 10/5, 2020 at 12:12 Comment(1)
For documenting optional parameters properly, see: #61712160Thibeault

© 2022 - 2024 — McMap. All rights reserved.