Calculating Costs
Introduction
Section titled โIntroductionโNow that weโve validated the information coming through from the user, we can start calculating the costs for the customer.
Weโll create a function that will take the userโs input, calculate the final costs for the customer and then return
an object that packages all this information together.
Creating a new function
Section titled โCreating a new functionโLetโs start by creating a new function called calculateCosts
that will take the userโs input as an argument.
-
We will follow the same approach as before, and create a new JavaScript module (file) called
calculateCosts.js
to split our data into small, manageable chunks. -
Inside this new file, add the code shown below:
calculateCosts.js export function calculateCosts(data) {console.log('Calculating costs...');console.log({ data });} -
Now, we need to
import
this function into our mainindex.js
file and call it with the userโs input.
Calculating Costs
Section titled โCalculating CostsโNow that we have our function set up, we can start calculating the costs for the customer.
Summary
Section titled โSummaryโIn this guide, we have:
- Created a new function called
calculateCosts
that takes the userโs input as an argument. - Stored in this new function in a new JavaScript module (file) called
calculateCosts.js
to help manage our code. - Calculated the total cost for the customer based on the userโs input.
- Used the
toFixed()
method to round the total cost to two decimal places. - Returned an object that packages all this information together and printed it to the console.
Next steps
Section titled โNext stepsโIn the next guide, we will display the total cost to the user.