0

I'm practicing my coding and I'm still kind of new. While looking for solutions to practice problems I see this kind of code used in loops and I'm curious what this line of code does.

counter[string[i]] = (counter[string[i]] || 0) + 1; 

here it is in the full code that is used to count most occured character in a string if this helps

var string  = "355385",
    counter = {};

for (var i = 0, len = string.length; i < len; i += 1) {
    counter[string[i]] = (counter[string[i]] || 0) + 1;
}

var biggest = -1, number;
for (var key in counter) {
    if (counter[key] > biggest) {
        biggest = counter[key];
        number = key;
    }
}

console.log(number);
Chris Bryant
  • 123
  • 7

1 Answers1

0

It is basically saying

If counter[string[i]] is falsy (undefined, 0, empty string, null etc) use 0 to add to 1 otherwise use its existing value to add to 1 and make this addition the new value for counter[string[i]]

It is using the logical OR operator ||

See JavaScript OR (||) variable assignment explanation

Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150