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.

Share:
17,278
Jarod Meng
Author by

Jarod Meng

Updated on June 10, 2022

Comments

  • Jarod Meng
    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
    Dev Null almost 5 years
    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 =
  • Magne
    Magne about 4 years
    For documenting optional parameters properly, see: stackoverflow.com/questions/61711660/…