javascriptbeginner10 minutes

Refactor Messy JavaScript Function for Calculating Total Price

Improve the readability and simplicity of a basic function that calculates the total price of items including tax by refactoring the provided messy code without changing its behavior.

Challenge prompt

You are given a function that calculates the total price after adding tax for a list of item prices. However, the code is messy and hard to read. Refactor the function to improve readability and code quality, keeping the same behavior and output. Requirements: - Use meaningful variable names. - Simplify the calculation if possible. - Remove any redundant code. Return the total price rounded to two decimal places.

Guidance

  • Make sure to keep the original functionality intact after refactoring.
  • Consider using array methods like reduce to simplify summing prices.

Hints

  • Check if any variables or steps are unnecessary and can be combined.
  • Use descriptive names to make the purpose of each variable clear.

Starter code

function calculateTotal(prices, taxRate) {
  var t = 0;
  var i = 0;
  for(i=0; i < prices.length; i++) {
    t = t + prices[i];
  }
  var totalPrice = t + (t * taxRate);
  return totalPrice.toFixed(2);
}

Expected output

calculateTotal([10, 20, 30], 0.1) // returns "66.00"

Core concepts

functionsloopsvariablesarray methodscode readability

Challenge a Friend

Send this duel to someone else and see if they can solve it.