Skip to main content

Functions and Closures

Default Parameters and Rest/Spread in Functions

0:00
LearnStep 1/3

Flexible Function Signatures

Modern JavaScript provides powerful tools to make function signatures more flexible and expressive. Instead of relying on manual checks for undefined or using the array-like arguments object, you can use default parameters and rest syntax.

Default Parameters

Default parameters allow you to initialize named parameters with default values if no value or undefined is passed.

javascript

Rest Parameters

Rest parameters allow a function to accept an indefinite number of arguments as an array. It must be the last parameter in the definition.

javascript

Spread Syntax in Calls

While rest collects arguments into an array, the spread operator (...) does the reverse: it expands an array into individual arguments during a function call.

javascript

Options Objects

For functions with many parameters, especially optional ones, using a single object parameter (often called 'options') is more readable than a long list of arguments. Combining this with destructuring and default values is a common idiomatic pattern.

javascript