ForEach method not working


let price = [0]

let items = [3, 4, 2, 5]

function cashier(cash){

     items += cash



}

items.forEach(cashier)

console.log(+price)


It pops up 3425 in console instead of total.

So… let me see if i can follow your code here. Walk with me, and through a little rubber duck debugging, we can probably find out whats going wrong.

Price is an array with a singular value - 0.
Items is an array with 4 values - 3,4,2 and 5.

You take each item from items, and pass it to the cashier function. So it starts with 3.
cash now has the value of 3.
you say items += cash.
That translates as items = items + cash.

But that doesnt make sense. You cant perform a mathematical operation on an array.
So Javascript has a little panic, tries to find a way to interpret these operands so they CAN have a + between them.

Javascript’s abort option is… “make the array a string. I can do + with strings, it means append.”
So it says items = “3425” + 3.
a string plus an integer translates the 3 into a string as well…
you end up with “34253”. (You then also immediately abort, because “items” is now a string, and the forEach falls apart)

If you want the total, then price shouldnt be an array, it should just be an integer. Also you shouldnt be trying to add to items, you should be trying to add to price?

3 Likes

:joy: I hadn’t understood the concept because the tutorials I watched don’t really explain it well. or maybe I’m just slow

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.