0

Code

function Taxes(taxRate, purchases) {
    let total = 0;
    console.log(purchases);
    for (let i = 0; i <= purchases.length; i++) {
        total += purchases[i];
    }
    console.log(total);
    return total * (taxRate/100 + 1);
}
console.log(Taxes(18, [15, 34, 66, 45])); 

Explanation

I attempted to make a tax adder. The program adds the given list of array(the price of things that've been bought), add them together and multiply the answer with the tax rate. I converted it into python code and it works flawlessly.

However i encountered an error where in the for loop, the total is not summed with the indexed value so it gives an undefined error when i try to log it. I tried to replace it with a number and it works. But when i use a variable, it doesn't. How do i use a variable to pick an index.

SideNote

I know that i don't have to use a for loop to sum up the numbers in the array, but let's say i want to do it this way

Gaenox L
  • 9
  • 2
  • 3
    _"the total is not summed with the indexed value"_ - It is. _"it gives an undefined error when i try to log it"_ - Because arrays are zero-indexed, and therefor the last element is at index `purchases.length - 1` -> `i <= purchases.length` should be `i < purchases.length` – Andreas Jul 02 '21 at 11:50
  • [What is an off-by-one error and how do I fix it?](https://stackoverflow.com/q/2939869) – VLAZ Jul 02 '21 at 14:05

1 Answers1

0

Your code is pretty much working. But you get an error, because Javascript array indices are zero-based: if your array has 4 elements, you address the elements starting with array[0] to array[3]. Therefore the loop condition in your for loop must be i < purchases.length instead of i <= purchases.length.

function Taxes(taxRate, purchases) {
    let total = 0;
    console.log("Purchases:", purchases);
    for (let i = 0; i < purchases.length; i++) {
        total += purchases[i];
    }
    console.log("Total: ", total);
    return total * (taxRate/100 + 1);
}
console.log("Total incl. tax:", Taxes(18, [15, 34, 66, 45])); 
Mario Varchmin
  • 3,704
  • 4
  • 18
  • 33
  • Oh i see. Because i added an if equal element, it doesn't stop the loop when i is not smaller anymore. Thanks for the help! I was really scratching my head – Gaenox L Jul 02 '21 at 20:17