Reputation: 5997
Given a string, I need to get the number of occurrence of each character in the string.
Input : "Hello world"
Expected Output : { H: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
When I use if else condition the logic works fine , but not with ternary operator.
const string = "Hello world";
const chars = {};
for(let char of string) {
if(!chars[char]) chars[char] = 1;
else chars[char]++;
}
console.log(chars); // { H: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
But, When I replace the if else condition with ternary operator, the output is unexpected
chars[char] = !chars[char] ? 1: chars[char]++
console.log(chars); // { H: 1, e: 1, l: 1, o: 1, ' ': 1, w: 1, r: 1, d: 1 }
Upvotes: 1
Views: 787
Reputation: 123553
In this case, you'll want to move the ++
before chars[char]
:
chars[char] = !chars[char] ? 1 : ++chars[char]
Or just an addition:
chars[char] = !chars[char] ? 1 : chars[char] + 1
Or, even shorter:
chars[char] = (chars[char] || 0) + 1
Whether you place the ++
before or after a value changes the value it returns:
After (chars[char]++
), the operator will return the original value, 1
, as it increments to 2
. The assignment operator, then, will receive the 1
and place it back into chars[char]
, undoing the increment.
Before (++chars[char]
), the operator will return the modified value, 2
, for the assignment to use. Here, the operators aren't in conflict with each other, as they're both setting the same value.
Upvotes: 3
Reputation: 22011
You are setting chars[char]
to the result of chars[char]++
which is 0
You want: chars[char] = !chars[char] ? 1: chars[char]+1
Upvotes: 1