29

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 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 =
This old answer is no longer correct and should be deleted. For a correct answer, see my quote of quoted Rafa Gullermo's answer from a duplicate question.
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.

2 Comments

For documenting optional parameters properly, see: stackoverflow.com/questions/61711660/…
You can also have rest parameters.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.