Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

432
Visualizações
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...

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Santiago Gelvez Relatório

0

You're conflating the ternary with the assignment expression.

The code

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

can also be written as

counts[ch] = (count ? count + 1 : 1);
// but not (counts[ch] = count) ? count + 1 : 1
// that does something entirely different

And then, writing the matching if/else becomes pretty clear

if (count) {
   counts[ch] = count + 1;
} else {
   counts[ch] = c1;
}
about 4 years ago · Santiago Gelvez Relatório

0

Well, This is a condition.

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

Corresponding if-else statement:-

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

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda