JavaScript中reduce方法里||运算符与初始值{}的作用解析
Hey there! Let's break down those two confusing parts of the reduce code you're working with—super common questions when you're new to JavaScript's reduce method, so you're totally on the right track.
1. What does the || operator do in tally[fruit] = (tally[fruit] || 0) + 1?
This line is all about avoiding messy NaN errors when we first encounter a new fruit. Let's walk through it with an example:
- When we hit a fruit for the first time (like
"apple"),tally[fruit]will beundefined—since our tally object doesn't have an"apple"key yet. - In JavaScript,
undefinedis a "falsy" value. The||(logical OR) operator uses a shortcut: if the left side is falsy, it takes the right side instead. Soundefined || 0evaluates to0. - We add
1to that0, getting1, then assign it back totally["apple"]—now our tally looks like{ apple: 1 }.
For repeat fruits:
tally[fruit]will already have a number (like1for"apple"), which is "truthy". The||operator sticks with this truthy value, so we do1 + 1to get2, updating the tally to{ apple: 2 }.
In short, the || 0 acts as a safety net—it makes sure we always start counting from 0 for new fruits, instead of trying to add 1 to undefined (which would give NaN).
2. What does the , {} at the end of the reduce method mean?
The reduce method takes two core arguments: a callback function (your counting logic) and an initial value. That {} is the initial value we're passing to the accumulator (the tally variable in your code).
Here's why it's non-negotiable:
- When you pass
{}, the first time your callback runs,tallystarts as an empty object. This lets us build up our fruit counts from a clean slate. - If you skipped this initial value,
reducewould default to using the first element of your array as the starting accumulator. For example, if your array was["apple", "banana", "apple"],tallywould start as"apple"(a string, not an object). Trying to dotally[fruit]on a string would throw errors—you can't assign properties to a string like you can an object!
So the , {} ensures our accumulator is a proper object ready to hold our fruit count data.
内容的提问来源于stack exchange,提问作者Alwaysblue

