0

can you explain how works letters[pass[i]] = (letters[pass[i]] || 0) + 1?

einar
  • 13
  • 6

2 Answers2

2

This line adds letters from pass to the letters object as keys and it's number of occurs in the value.

So, for example, for pass = "aabbc" you'll have letters equal to

{
  "a":2,
  "b":2,
  "c":1
}

The operator on the right ((letters[pass[i]] || 0) + 1) can be splitted to two: letters[pass[i]] || 0 checks if letters has key of value pass[i], if so the expression will have it's value, if not then we will get value after || - in this case 0. To value of this expression we add always 1.

Also, we could convert this one line to something like this:

if(letters[pass[i]]) {
  letters[pass[i]]++;
} else {
  letters[pass[i]] = 1;
}

About the || operator in value assignment you can read more for example here

Adrian Kokot
  • 2,172
  • 2
  • 5
  • 18
1

Let's start from the inside out, like JavaScript does. :-)

(letters[pass[i]] || 0) + 1

That:

  • Starts with pass[i] which gets the letter for index i from pass (which appears to be a string)
  • Then tries to get the value for a property with that name from letters (letters[pass[i]]). It will either get a number that it's put there before or, if there is no property for that letter (yet), it'll get the value undefined.
  • It uses that value (a number or undefined) with (the value) || 0. The || operator works fairly specially in JavaScript: It evaluates its left-hand operand and, if that value is truthy, takes that value as its result; otherwise, it evaluates its right-hand operand and takes that value as its result. undefined is a falsy value, so undefined || 0 is 0. This is to handle the first time a letter is seen.
  • It adds 1 to the result it got from ||.

Basically, that's adding one to the value of the property for the letter on letters, allowing for never having seen that letter before via ||.

Then it stores the result back to the property.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875