Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ternary operator -- what is the condition?

I read a handful of SOF posts on ternary operators but I'm still confused with this example:

var str = "I want to count";
var counts = {};
var ch, index, len, count;

for (index = 0; index < str.length; ++index) {
    ch = str.charAt(index); 
    count = counts[ch];
    counts[ch] = count ? count + 1 : 1; // TERNARY
}

I know the syntax is condition ? expression1 : expression2

But I am trying to practice and break up the ternary into an if-else.

I don't know what the condition is supposed to be

counts[ch] = count // this isn't a condition, it's assigning a value...

like image 660
Lewis Avatar asked Oct 14 '25 20:10

Lewis


1 Answers

The ternary

counts[ch] = count ? count + 1 : 1;

The condition in this expression is not counts[ch] = count but just count and is equivalent to

if (count){
    counts[ch] = count + 1;
}
else {
    counts[ch] = 1;
}

The right hand side of an assignment expression is always evaluated first and the counts[ch] is assigned the result of count ? count + 1 ? 1.

like image 81
phuzi Avatar answered Oct 17 '25 10:10

phuzi