Default parameters
When you create functions, you can provide each parameter with a default value. Here’s how you do it.
const calculateTaxes = (income, taxRate = 0.17)
=> income * taxRate
If the user uses calculateTaxes
without passing in taxRate
, taxRate
will default to 0.17.
If the user passes in a tax rate, the taxRate
will be the value passed in by the user.
// With default tax rate
console.log(calculateTaxes(100)) // 17
console.log(calculateTaxes(100, 0.15)) // 15
Default parameters are great because they let your users use your function without writing additional arguments—lesser work on their part (or yours, if you’re using the function).
Optional destructured parameters
When a function requires four (or more) parameters, users can find it difficult to remember the order of arguments to pass in.
Take for example, the createUser
function below. What if you passed email
as the first argument by accident?
const createUser = (firstName, lastName, email, password, location) => {
// ...
}
createUser('Zell', 'Liew', '[email protected]', '12345678', 'Singapore')
When your function requires many parameters, it makes sense to pass an object instead. This way, users won’t have to remember the order of arguments. They just need to make sure everything is passed in.
const createUser = (user) => {
const { firstName, lastName, email, password, location } = user
// ...
}
createUser({
email: '[email protected]',
password: '12345678',
firstName: 'Zell',
lastName: 'Liew',
location: 'Singapore'
})
Let’s say you’re building an app for Singaporeans. In this case, the location
parameter can be set to Singapore
by default.
Here’s one way to do so:
const createUser = (user) => {
const {
location = 'Singapore'
} = user
// ...
}
Another way (which is quite popular) is to destructure the parameter directly. To do so, parameter must be optional (defaults to empty object).
const createUser = (user = {}) => {
// ...
}
Next, you destructure the object; when you do so, you provide a default value to location
.
const createUser = ({
firstName,
lastName,
email,
password,
location = 'Singapore'
} = {}) => {
// ...
}
Note: I prefer the first method because I can still use the user
object. In the second method, I lost the user
object; I can only use the destructured variables.
Exercise
- Create a function,
signUpForPlan
, that takes in one parameter, plan
. plan
defaults to basic
- Create a function,
createEmployee
that takes in an object that has five properties:
- First Name
- Last Name
- Age
- Gender
- Position (default position to
associate
)