Tag Archives: forEach cannot exit the loop

How to Solve forEach cannot exit the loop Issue

The forEach loop in the array will report an error if you want to exit the whole loop using break, and return will not jump out of the loop. In other words, the forEach traversal cannot be terminated.

Solution:

Iterate through for to achieve

    let arr = ['1', '2', '3', '4', '5'];
     for(let i=0; i<arr.length; i++) {
       if(arr[i] == '3') break;
       console.log(arr[i]) // 1 2
     }

Implemented by try--catch throwing exceptions

    let arr = ['1', '2', '3', '4', '5'];
    try {
      arr.forEach((item, index) => {
        if (item === '3') {
          throw new Error('End')
        }
        console.log(item) // 1 2 
      })
    } catch (e) {
      if (e.message === 'End') throw e;
    }

Implemented via reduce iteration, with an interrupt flag set

    let arr = ['1', '2', '3', '4', '5'];
    arr.reduce(function (p, c) {
      if (c == '3') {
        this.break = true
      }
      if (this.break) {
        return
      }
      console.log(c) // 1 2
    }, '')