What are default parameters and how are they used?
TL;DR
Default parameters in JavaScript allow you to set default values for function parameters if no value or undefined
is passed. This helps avoid undefined
values and makes your code more robust. You can define default parameters by assigning a value to the parameter in the function definition.
Default parameters
Default parameters in JavaScript provide a way to set default values for function parameters. This feature was introduced in ECMAScript 2015 (ES6) and helps to make functions more robust and easier to work with by avoiding undefined
values when no arguments are passed.
Syntax
You can define default parameters by assigning a value to the parameter in the function definition. If no value or undefined
is passed for that parameter, the default value will be used.
Example
Here is a simple example to illustrate how default parameters work:
In this example, the greet
function has a default parameter name
with a default value of 'Guest'
. When the function is called without any arguments, it uses the default value. When an argument is provided, it overrides the default value.
Multiple default parameters
You can also define multiple default parameters in a function:
In this example, the createUser
function has two default parameters: username
and age
. If no arguments are passed, both default values are used. If only one argument is passed, the second parameter uses its default value.
Using expressions as default values
You can also use expressions as default values for parameters:
In this example, the default value for b
is an expression that depends on the value of a
. If no arguments are passed, a
is 0
and b
is 1
. If only a
is passed, b
is a + 1
. If both a
and b
are passed, the provided values are used.