Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Apps Script, How to include optional arguments in custom functions

Tags:

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?

like image 345
Jarod Meng Avatar asked Jun 01 '12 02:06

Jarod Meng


People also ask

How do you make an optional argument a function?

You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.

How do you pass optional arguments in JavaScript?

To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.

Can you have optional arguments in JavaScript?

Optional parameters are great for simplifying code, and hiding advanced but not-often-used functionality. If majority of the time you are calling a function using the same values for some parameters, you should try making those parameters optional to avoid repetition.

What is an optional argument in functions?

Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.


1 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.

like image 178
Eric Koleda Avatar answered Oct 12 '22 17:10

Eric Koleda