When you create functions, you can provide each parameter with a default value. Here’s how you do it.
function calculateTaxes(income, taxRate = 0.17) { return 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 rateconsole.log(calculateTaxes(100)) // 17console.log(calculateTaxes(100, 0.15)) // 15Default 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?
function createUser(firstName, lastName, email, password, location) { // ...}
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.
function createUser(user) { const { firstName, lastName, email, password, location } = user // ...}
createUser({ 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:
function 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).
function createUser(user = {}) { // ...}Next, you destructure the object; when you do so, you provide a default value to location.
function 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.plandefaults tobasic - Create a function,
createEmployeethat takes in an object that has five properties:- First Name
- Last Name
- Age
- Gender
- Position (default position to
associate)
Create a function, signUpForPlan, that takes in one parameter, plan. plan defaults to basic.
const signUpForPlan = (plan = 'basic') => { // Stuff}Create a function, createEmployee that takes in an object that has five properties:
- First Name
- Last Name
- Age
- Gender
- Position (default position to
associate)
const createEmployee = ( firstName, lastName, age, gender, position = 'associate'= {}) => { // Stuff}Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson