HomeContact
Javascript
How to break out of a for loop or jumps over one iteration in Javascript
June 01, 2020
1 min

There is two possibility to interact in a for loop in Javascript:

  • You can either break it (jumps out), so that it directly stop, using break,
  • Or you can simply pass an iteration and do nothing (jumps over) , but continue the for loop, for that it would be continue.

For example, to stop a for loop it will be :

for (i = 0; i < 8; i++) {
  if (i === 3) {
    break
  }
  console.log(`We are in the ${i} loop. Loop after 2 will not show`)
}

To simply jump the fourth loop, we can do :

for (i = 0; i < 8; i++) {
  if (i === 3) {
    continue
  }
  console.log(`We are in the ${i} loop. Loop after 3 will be ignored`)
}

Those also work with for ... of loop :

const list = ['a', 'b', 'c']

for (const value of list) {
  if (value === 'a') {
    continue
  }
  console.log(`The value are ${value}, a will be ignored`)
}

Note that those will not work with forEach statement.


Tags

javascript

Related Posts

How to remove space from String using Javascript
February 04, 2021
1 min
© 2022, All Rights Reserved.

Quick Links

Contact Us

Social Media