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

Time:10-10

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

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)

CodePudding user response:

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)

CodePudding user response:

Use Array.every() to perform the loop. As soon as False is returned, the looping ends. Here is an example.

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

const iterate = (arr, callback) => {
  search: arr.every(compare) 
}

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

iterate(myArr, compare)
  • Related