function calculateTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
if (items[i].type === "food") {
total += items[i].price * 1.1;
} else {
total += items[i].price;
}
}
return total;
}
const items = [
{ type: "food", price: 10 },
{ type: "clothing", price: 20 },
{ type: "electronics", price: 30 }
];
console.log(calculateTotal(items));
I need to improve on this code.
I have tried improving the variable description. here is the code again with improved variables
function calculateTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.type === "food") {
total += item.price * 1.1;
} else {
total += item.price;
}
}
return total;
}
const items = [
{ type: "food", price: 10 },
{ type: "clothing", price: 20 },
{ type: "electronics", price: 30 }
];
console.log(calculateTotal(items));
what else can i try improving on in this code?
You can add a factor const with shorted if syntax for better readability
Or using
forEachJavaScript syntax you can use:Also, you can add factor property inside the item object itself to 'special' items (with factor != 1) like this:
Than you can use the
reducemethod like this:Or just: