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?
In Apps Script, How to include optional arguments in custom functions
Asked Answered
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.
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.
For documenting optional parameters properly, see: #61712160 –
Thibeault
© 2022 - 2024 — McMap. All rights reserved.
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