easyLogic ErrorsJavaScript
The empty trap
A developer asked an AI assistant to compute the average rating from a list of review scores for a product page. The suggested code works great for every product with reviews, but the page crashes entirely for new products that have zero reviews yet.
ratings.js
function averageRating(reviews) {
const total = reviews.reduce((sum, r) => sum + r.score);
return total / reviews.length;
}What happens when averageRating([]) is called for a brand-new product?
TypeError: Reduce of empty array with no initial value — reduce needs a seed value to handle an empty array.
It returns 0, since there are no scores to sum.
It returns NaN silently without throwing.
It returns undefined without throwing.