user5522689
user5522689

Reputation:

Why does this method for counting duplicates of an array and storing it into an object work?

var counts = {};
var your_array = ['a', 'a', 'b', 'c'];
your_array.forEach(function(x) { 
  counts[x] = (counts[x] || 0) + 1; 
});
console.log(your_array);

In javascript, why do you have to do counts[x] = (counts[x] || 0) + 1; Why doesn't counts[x] += 1; work?

This will output { a: 2, b: 1, c: 1}, but why?

Upvotes: 0

Views: 24

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386670

The problem ariesed if counts[x] is undefined. In this case, an increment does not work. The logical "or" (||) evaluates the value on the left side and if that value is falsy, the right part is taken.

So for example, if you separate the line, you get

counts[x] || 0

that returns either the truthy value of counts[x], if undefined, false, null, even 0 then the right part with value of 0.

The addition and assignment should be clear.

Right from MDN:

In JavaScript, a truthy value is a value that translates to true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

Upvotes: 1

Related Questions