Skip to content

Calculating Costs

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.

Letโ€™s start by creating a new function called calculateCosts that will take the userโ€™s input as an argument.

  1. 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.

    Add calculate costs module

  2. Inside this new file, add the code shown below:

    calculateCosts.js
    export function calculateCosts(data) {
    console.log('Calculating costs...');
    console.log({ data });
    }
  3. Now, we need to import this function into our main index.js file and call it with the userโ€™s input.

Now that we have our function set up, we can start calculating the costs for the customer.

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.

In the next guide, we will display the total cost to the user.