开发者

Why do we use breaks in JavaScript loops?

I know "break" is used to stop a loop before the satisfaction of a 开发者_如何学JAVAparticular condition but I am really confused WHY use break when we have the option to make our criteria better. For example look at this piece of code:

var i = 0;
for (i = 0; i <= 10; i++) {
    if (i == 3) {
        break;
    }
    document.write("The number is " + i);
    document.write("<br />");
}

I know it very well that this break command will terminate the loop as the value of the variable reaches to 3 but my question is why we use break instead of making our condition like i<=3. Can someone make it clear with some practical example?


A simple example would be where you are looping through objects in an array, looking for one that satisfies a certain condition. When you've found that object, you don't need to check the rest so use break.


for (var i = 0; i < arr.length; i++) {
  var e = arr[i];
  if (someCondition(e)) {
    break;
  }
}
// use e

vs

for (var i = 0; !someCondition(arr[i]); i++);
var e = arr[i];
// use e

Yes you can have a better condition but that means your putting logic in the for loop statement rather then the body. This can quickly lead to unreadable code.

break and continue are more readable


For example when you're searching something in an array of 10 items, you want to loop from 0 .. 9. However, as soon as a result is found, there's no use for searching further, so you can break and jump out of the loop.


In your example, its a bad loop condition.

However it would get really complicated when dealing with other objects. See my example.

var i = 0;
var myArrayOfObjects = ....
for (i = 0; i <= 10; i++) {
    if (myArrayOfObject[i].someProperty == 3) {
        break;
    }
    document.write("The number is " + i);
    document.write("<br />");
}


I'm pretty sure this is just a piece of code to show you how break works. In reality you wouldn't write anything like that.

However, break has it's advantages. You can exit the loop in any moment you want (not only when loop condition says so)


To add to what other people have said, sometimes you need to break only when a certain event is fired. Code similar to this:

while(true)
{
//run application
if(event)

   break;


}
//end application

makes sense in the context of many applications, games especially.

Also, sometimes you may need to check for a condition in the middle of the loop and not in the start of it, so using break does not just make code more readable, it's essential in some cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜