Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda