Default Function Parameters

Web Developer | React.js | JavaScript | Check out my blog: https://blog.eligarlo.dev
Search for a command to run...

Web Developer | React.js | JavaScript | Check out my blog: https://blog.eligarlo.dev
Thanks a lot, Francesco!
React is a popular JavaScript library that provides developers with a powerful and efficient way to build user interfaces. One of the key features of React is the ability to use a method called createPortal to render components outside the main conte...

For a good work-life balance, stay active and healthy.

A few days ago I decided it was time for me to update myself to the new version of Vuejs, Vue 3. And today I wanted to share with you the first thing I learn that version two didn't have, the teleport component. It's well known that modern web applic...

Definition of trim, "To cut away unnecessary parts from something." - Oxford Dictionary. Sometimes, validating forms in JavaScript can be a tedious task for a developer. You have to check many things. For instance, that the values given are of the t...

We always have to validate if the arguments passed in a function have a value or they are undefined but, do we really?
In my last post, I talked about Destructuring Assignment In A Function Parameter and why it is handy when you have optional parameters in a function and don't want to pass undefined or null.
With that been said, what if you have a function where all the parameters are required? Again, since ES2015 (aka ES6) this can be easily implemented. Let's dive in.
If you take a Tip Calculator project as an example, you probably will need always the same parameters:
The function you'll need would look like this 👇
function calculateTip(totalBill, numOfPeople, serviceQuality) {
// Your validation here
// Your code here
}
console.log(calculateTip(50, 2 , 0.2))
// 5.00
Inside the function, you'll have to do all the calculations AND all the validation; plus, most of the time I go with the same friend (2 people) and leave the standard tip (20%).
In this case, the only parameter that will be changing all the time will be the bill amount.
So, let's give numOfPeople and serviceQuality a default parameter:
function calculateTip(totalBill, numOfPeople = 2, serviceQuality = 0.2) {
// Your code here
}
console.log(calculateTip(50))
// 5.00
console.log(calculateTip(75))
// 7.50
Now, just when someone else is joining, or we want to leave a different tip percentage, it will be necessary to pass the rest of the arguments.
You don't really need to check if the argument in a function is undefined, you can create a default value for it.
When a different value is provided, the default value will be overwritten.
If you found it useful, please like, subscribe, and share the knowledge.
You might like what I share on my Twitter too.