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

168
Visualizações
Is JavaScript Conditional Operator better method for this if/else statement?

I am trying to see if I can reduce the code below with less JavaScript. When the user select Even dropdown option the only differences between that and the else statement is "i = 0" and "i % 2 === 0"

any recommendations? Maybe conditional operator would be best method? thank you

        if (this.selection == "even") {
            for (let i = 0; i <= number; i++) {
                if (i % 2 === 0) 
                this.results.push(i + "\n");
            }
        } else {
            for (let i = 1; i <= number; i++) {
                if (i % 2 !== 0) 
                this.results.push(i + "\n");
            }
        }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use this.selection to determine the starting number, then increment by 2 inside the loop instead of i++, so you don't have to check i % 2.

const startAt = this.selection == "even" ? 0 : 1;
for (let i = startAt; i <= number; i += 2) {
    this.results.push(i + "\n");
}
about 4 years ago · Juan Pablo Isaza 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