can you explain how works letters[pass[i]] = (letters[pass[i]] || 0) + 1?
2 Answers
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
- 2,172
- 2
- 5
- 18
-
thanks, nice explanation! – einar Oct 22 '21 at 09:23
-
Hi Adrian, I already did that, but I am new at stack-ow, so I believe I don't have enough exp for the mark to be counted. – einar Oct 26 '21 at 09:48
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 indexifrompass(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 valueundefined. - 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.undefinedis a falsy value, soundefined || 0is0. This is to handle the first time a letter is seen. - It adds
1to 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.
- 1,031,962
- 187
- 1,923
- 1,875