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.