How to break through the for loop in JavaScript

Find out how to break the for or for...of loop in JavaScript

Say you have oneforRing:

const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
  console.log(`${i} ${list[i]}`)
}

If you want to break through at some point, please state the time to reach the elementb,you can use itbreakstatement:

const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
  console.log(`${i} ${list[i]}`)
  if (list[i] === 'b') {
    break
  }
}

you can use itbreakAlso broke the for..of loop:

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

for (const value of list) { console.log(value) if (value === ‘b’) { break } }

Note: Can't break throughforEachLoop, so (if needed) usefororfor..of.

Download mine for freeJavaScript beginner's manual


More js tutorials: