Skip to main content

Introduction

Optional parameters allow you to call functions with or without providing all arguments. This makes functions more flexible when some values aren’t always needed.

Optional Parameter Syntax

Wrap optional parameters in square brackets [] and provide default values:

Key Components

  • Required parameter: String nombre - must always be provided
  • Square brackets: [] - indicate optional parameters
  • Default value: = 'Sin Ciudad' - used when the parameter is not provided

Using Optional Parameters

With Default Value

When you don’t provide the optional parameter, the default value is used:

With Provided Value

When you provide the optional parameter, your value overrides the default:

Complete Example

Multiple Optional Parameters

You can have multiple optional parameters:
Optional positional parameters must be provided in order. You cannot skip an optional parameter and provide a later one.

Default Values

String Defaults

Numeric Defaults

Boolean Defaults

Nullable Optional Parameters

You can make optional parameters nullable without default values:
Use the ? suffix to make a parameter nullable when you don’t want to provide a default value.

Optional vs Required

Required Parameters

  • Must be provided when calling the function
  • Come before optional parameters
  • No square brackets needed

Optional Parameters

  • Can be omitted when calling the function
  • Come after required parameters
  • Enclosed in square brackets

When to Use Optional Parameters

  • When a parameter has a sensible default value
  • When some function features are only needed occasionally
  • To maintain backward compatibility when adding new parameters
  • To reduce the number of function overloads

Best Practices

  • Always provide meaningful default values
  • Don’t create too many optional parameters (3 or fewer is ideal)
  • Consider using named parameters instead if you have many optional parameters
  • Document what the default values mean
If you need to skip optional parameters in the middle, consider using named parameters instead of positional optional parameters.

Comparison Table