Is it possible to do this kind of code in the ternary operator in javascript? If yes, I think I'm doing it wrong, when I tried the code below I wrote it just return the whole function(){}
method
let products = [
{
price: 2.6,
quantity: 5,
},
{
price: 5.9,
quantity: 5,
},
{
price: 2.3,
quantity: 5,
},
{
price: 4.9,
quantity: 5,
}
];
let sumtotal = products.length > 1 ? function(){
let total = 0;
for(const { price, quantity } of products) {
total += (price * quantity);
}
return parseFloat(total).toFixed(2);
} : function() {
let total = (products[0].price * products.quantity);
return parseFloat (total).toFixed(2);
};
console.log(sumtotal);
I was hoping that this would return an actual value like the output would be an Integer
or float
.