Reputation: 71
I have this piece of code (it is part of a large javascript code) and I want it to return 'article' or 'articles' as well as the quantity.
If the var quantity = 1, it should return '1 article'. If the var quantity = 0 or any other number, it should return 'x articles'
quantity: function () {
var quantity = 0;
simpleCart.each(function (item) {
quantity += item.quantity();
});
return quantity;
},
Can someone please show me how to do this? Thanks in advance.
Upvotes: 0
Views: 79
Reputation: 2685
return quantity==undefined?'':quantity==1?'1 Article':quantity+' Articles';
Upvotes: 1
Reputation: 29668
A simply ternary would work:
quantity: function () {
var quantity = 0;
simpleCart.each(function (item) {
quantity += item.quantity();
});
return quantity + (quantity == 1 ? ' Article' : ' Articles');
};
As you've said you're new to JavaScript, the ?:
operator is basically a compact form of if
in the form expression ? when-true : when-false
.
Upvotes: 3
Reputation: 1554
quantity: function () {
var quantity = 0;
simpleCart.each(function (item) {
quantity += item.quantity();
});
return (quantity == 1) ? '1 article' : $quantity + ' articles';
}
Upvotes: 1