Can someone explain to me the differences between these examples please?
Here's the original code.
const items = [
{ name: "Bike", price: 100 },
{ name: "TV", price: 200 },
{ name: "Album", price: 10 },
{ name: "Book", price: 5 },
{ name: "Phone", price: 500 },
{ name: "Computer", price: 1000 },
{ name: "Keyboard", price: 25 },
];
const total = items.reduce((total, amount) => {
return total + amount.price;
});
console.log("total", total);
above returns total [object Object]200105500100025
<- what is this [object Object] and also why is the result 200105500100025 instead of 1840?
const total = items.reduce((total, amount) => {
return total + amount.price;
}, 0);
this code returns total 1840
which is what I was looking for but why does having ,0); at the end change this result? Does it change the price values to 'numbers' instead of an 'object' or 'string' like the above?
I noticed that some tutorails on YouTube say that because it's an arrow function I don't need to type 'return' and make the code look like:
const total = items.reduce((total, amount) => {total + amount.price}, 0);
But this returns me a result of total undefined
What's the difference between having return
and not having it?