1

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 }
2
  • Did you mean chars[char] + 1? Commented May 26, 2018 at 17:35
  • it does not make sense, to increment a variable and assign the value of the same variable to itself. Commented May 26, 2018 at 17:42

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes on the "even shorter" version, as it's also clearer!
@Prem With your if..else snippet, you aren't using the value returned from the ++ operator. Without assigning it anywhere, that return value is discarded and has no effect on the results of the script. In switching to ternary, you also began to assign the result of ++, making it more relevant.
@ScottSauyet There was a typo in my comment in this post, but I couldn't edit the typo. Hence I deleted it. Your comment clarifies my doubt.
1

You are setting chars[char] to the result of chars[char]++ which is 0

You want: chars[char] = !chars[char] ? 1: chars[char]+1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.