Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of a while loop from within an inner function's body

If I have:

while(foo) {
  var x = bar.filter(function(){ /* any problems with using `break;` here to exit the while-loop? */ });
  bar(), baz();
  // and so on...
}

Will there be any weird or unexpected behaviors?

like image 502
user3025492 Avatar asked Nov 27 '13 09:11

user3025492


1 Answers

break breaks the loop it appears directly within; if you have break outside of a loop (or switch) in a function (your filter iterator), it's a syntax error.

Add a condition to the while which is set by the function:

var stop = false;
while(foo && !stop) {
  var x = bar.filter(function(){
    if (someCondition) {
        stop = true;
    }
  });
  bar(), baz();
}

Or of course, it could just set foo directly:

while(foo) {
  var x = bar.filter(function(){
    if (someCondition) {
        foo = false;
    }
  });
  bar(), baz();
}

...but I don't know what foo is and whether that's reasonable.

If you need bar and baz not to be executed in the breaking condition, you'll need to add a guard:

var stop = false;
while(foo && !stop) {
  var x = bar.filter(function(){
    if (someCondition) {
        stop = true;
    }
  });
  if (!stop) {
      bar(), baz();
  }
}

or

while(foo) {
  var x = bar.filter(function(){
    if (someCondition) {
        foo = false;
    }
  });
  if (foo) {
      bar(), baz();
  }
}
like image 94
T.J. Crowder Avatar answered Sep 18 '22 14:09

T.J. Crowder