Adding an array of numbers in JS gets undefined because array doesn't accept variable to pick a value

445 Views Asked by At

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

1

There are 1 best solutions below

1
Mario Varchmin On

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]));