How to break/continue across nested for each loops in TypeScript

Typescript

Typescript Problem Overview


I tried to use break inside nested for each loop and it says jump target cannot cross function boundary. please let me know how can i break nested for each loop when certain condition is met in TypeScript.

groups =[object-A,object-B,object-C]
    groups.forEach(function (group) {
    // names also an array
        group.names.forEach(function (name) {
    
        if (name == 'SAM'){
         break; //can not use break here it says jump target cannot cross function boundary
      }
    
    }
    
    }

Typescript Solutions


Solution 1 - Typescript

forEach accepts a function and runs it for every element in the array. You can't break the loop. If you want to exit from a single run of the function, you use return.

If you want to be able to break the loop, you have to use for..of loop:

  for(let name of group.names){
    if (name == 'SAM') {
      break;
    }
  }

Solution 2 - Typescript

ForEach doesn't support break, you should use return

  groups =[object-A,object-B,object-C]
        groups.forEach(function (group) {
        // names also an array
            group.names.forEach(function (name) {
    
            if (name == 'SAM'){
             return; //
          }
     }
   }

Solution 3 - Typescript

Object.keys(fields).forEach(function (key, index) {
  if (fields[key] !== null && fields[key].toString().trim().length === 0) {
    console.log('error');
    return;
  }
});

Solution 4 - Typescript

I don't have enough reputation to comment, but when I tried Mahmoodvcs' answer, I got a compile error "Cannot find name "name"".

The solution is to declare your variable ahead of the loop, it won't be instantiated automatically as in a forEach. Simple solution, but you never know what might trip you up, so hopefully it helps somebody.

This snippet is the closest I could get to a forEach syntax with the desired behavior:

for(let name of group.names){
  if (name == 'SAM') {
    break;
  }
}

Also, my case was slightly different. I was using a return inside a forEach loop, but I intended the return to apply to the containing function, not the forEach. This does not return an error, so I was lucky I had viewed this post earlier or I might have been banging my head on my desk all day. My code went from:

 Object.keys(this.ddlForms).forEach(x => {
        if (!(!this.ddlForms[x].filterControl.value || this.ddlForms[x].filterControl.value[0] == 'All' || this.ddlForms[x].filterControl.value.some(y => y == data[this.ddlForms[x].fieldName]))) {//does not meet any of these three conditions
          return false;
        }
      });

to:

for(let x of Object.keys(this.ddlForms)) {
        if (!(!this.ddlForms[x].filterControl.value || this.ddlForms[x].filterControl.value[0] == 'All' || this.ddlForms[x].filterControl.value.some(y => y == data[this.ddlForms[x].fieldName]))) {//does not meet any of these three conditions
          return false;
        }
      }

Solution 5 - Typescript

If you're just interested in knowing if "Sam" is or is not in the list, consider using the .some method

if(group.names.some(name => name == 'SAM'))
    // Do logic here.

Solution 6 - Typescript

ForEach doesn't support break nor return. It says it supports return for forEach but it doesn't do anything in real. Here is the article that explains you clearly about this. If you use ".some" then it does return for sure once it finds the first item. You can use .some only if you want to return from loop as soon as you find the first item. If you want to do some operation on each element then use .foreach function.

https://www.knowledgescoops.com/2019/07/javascript-array-some-vs-every-vs_27.html

Solution 7 - Typescript

Instead of forEach(), try using for loops and labeled statements, just like in JavaScript:

outer: for (const i of [1,2,3]) {
    for (const j of [4,5,6]) {
        if (j === 6) break outer
        console.log(i, j)
    }
}
console.log('done')

Outputs:

1 4
1 5
done

You can test this on the TypeScript Playground.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiongihan-madurangaView Question on Stackoverflow
Solution 1 - TypescriptMahmood DehghanView Answer on Stackoverflow
Solution 2 - TypescriptlazydeveloperView Answer on Stackoverflow
Solution 3 - TypescriptAyoub EL ABOUSSIView Answer on Stackoverflow
Solution 4 - TypescriptDavid JonesView Answer on Stackoverflow
Solution 5 - TypescriptRyan DView Answer on Stackoverflow
Solution 6 - TypescriptInspiredDeveloperView Answer on Stackoverflow
Solution 7 - Typescripta paid nerdView Answer on Stackoverflow