0

Let's say I have an array of words, and I would like to use an object to get the count of it. I tried this:

const results = {};

const words = ["word", "hello", "code", "five", "hello", "word", "new", "code"];

words.forEach( word => {
  results[word] = results[word] + 1 || 1;  
});

results in this case returns:

{ word: 2, hello: 2, code: 2, five: 1, new: 1 }

NaN === false is false and results[word] + 1 => NaN. I don't quite understand why results wouldn't be:

{ word: NaN, hello: NaN, code: NaN, five: NaN, new: NaN }

Someone care to explain? :)

Peter Zhen
  • 16
  • 1

2 Answers2

3

results[word] when results doesn't contain word is undefined. Though NaN === false is false, it's still a falsy value (!!NaN is false).

Therefore, results[word] + 1 || 1 = undefined + 1 || 1 = NaN || 1 = 1.

Karin
  • 8,404
  • 25
  • 34
-1

undefined+1 = NaN

results[word] = results[word] + 1 || 1;

You're initializing the value at one where the || (or) operation sets the default to 1 instead of 0. The way I solved this was wrapping the condition like so:

results[word] = (results[word] || 0)+1;
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118