• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

120
Vistas
How to embed an if statement in a "for of" loop in JS

I have a genuine quetion. Given this simple JS code:

for (let x of array) {
   if (x != array[0]) {
       // do stuff
   }
}

Is there a way to embed the "if" statement directly into the for loop?

I tried something like this:

for (let x of array if x != array[0] {
   // do stuff    
}

And:

for (let x != array[0] of array) {
   // do stuff
}

But both of them didn't work. Let me know if you can find a solution!

about 3 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can filter the array with the condition and iterate through that result:

const array = [1, 2, 3]

for(let x of array.filter(e => e != array[0])){
    console.log(x)
}

about 3 years ago · Juan Pablo Isaza Denunciar

0

You cant pass a boolean in a "for of" or "for in" loops , the only way of do a comparison for an iteration of a loop is doing :

let array = ["37","728"];

for (let x = 0 ; ((x < array.length) && array[x] == "37") ; x++){
  console.log(array[x]);
}

And it will break the for loop if the second condition pass to true

about 3 years ago · Juan Pablo Isaza Denunciar

0

If you specifically only want to do stuff on the 2nd - nth element, you can just use a for loop and start at 1 instead of 0.

for (let i = 1; i < arr.length; i++) {
  // do stuff
}
about 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda