Search code examples
javascripthtmlcss

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


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!


Solution

  • 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)
    }