Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make another function aware of the loop name, so it can break it?

You see I have this code. (https://jsfiddle.net/kg4f2bu0/).

Inside my iterate function I use a label for my loop, because I want to break it if it meets a condition. The condition gets checked inside the callback function. I want to break the for..of loop inside my callback function (compare). But it doesn’t recognise the statement label. How can I make the callback function aware of the loop name?

This is JavaScript code. You can read information on label name here: https://javascript.info/while-for#labels-for-break-continue

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const myArr = [1, 2, 3, 4, 5, 6];

const iterate = (arr, callback) => {
  search: for (const item of arr) {
    callback(item)
  }
}

const compare = (num) => {
  console.log(num);
  if (num === 4) {
    console.log("breaking");
    break search;
  }
}

iterate(myArr, compare)

>Solution :

You cannot break out of a loop from inside another function. The reason for this is technical: the label for the break is resolved once, before your code starts running. So at runtime, it’s just a simple "goto"; it doesn’t go hunting up the call stack for a function containing a matching label. (What if there’s none? What if there are multiple?)

What you can do instead is return a boolean value that indicates whether the item was found, and thus whether the loop should break:

const myArr = [1, 2, 3, 4, 5, 6];

const iterate = (arr, callback) => {
  for (const item of arr) {
    if (callback(item)) {
      break;
    }
  }
}

const compare = (num) => {
  console.log(num);
  if (num === 4) {
    console.log("breaking");
    return true;
  }
  return false;
}

iterate(myArr, compare)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading