How To Use Conditional(ternary) Operator In Javascript
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
Solution 1:
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 to2
. The assignment operator, then, will receive the1
and place it back intochars[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.
Solution 2:
You are setting chars[char]
to the result of chars[char]++
which is 0
You want: chars[char] = !chars[char] ? 1: chars[char]+1
Post a Comment for "How To Use Conditional(ternary) Operator In Javascript"