I want to write a custom function which has some mandatory arguments but can also accept a few optional arguments. How can I do this?
3 Answers
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.
2 Comments
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 =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.
2 Comments
Both answers from 2012 and 2020 are incorrect.
Google Apps Script implements the ES2015 syntax for rest parameters. Quoting here Rafa Guillermo's answer from a later duplicate question, with a slight modification to illustrate optional parameters:
You can use function rest parameter syntax:
function COMPLEXSUM(...args) {
let sum = 0;
args.forEach(x => {
sum += x;
})
return sum;
}
or if you want some parameters to be required, some to have default values, and additionally some optional ones:
function COMPLEXSUM(param1, param2 = 0, ...args) {
let sum = param1 + param2;
return args.length === 0 ? sum : sum + args.reduce((pre, curr) => {
return pre + curr;
})
}
What's not clear is how to document these optional parameters. That seems impossible as of Nov 2024.