In Apps Script, How to include optional arguments in custom functions
17,278
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.
Author by
Jarod Meng
Updated on June 10, 2022Comments
-
Jarod Meng about 2 years
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?
-
Dev Null almost 5 yearsbetter 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 = -
Magne about 4 yearsFor documenting optional parameters properly, see: stackoverflow.com/questions/61711660/…