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 }
chars[char] + 1?