简体   繁体   中英

Why do we use breaks in JavaScript loops?

I know "break" is used to stop a loop before the satisfaction of a particular 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

例如,当您在10个项目的数组中搜索某些内容时,您希望从0开始循环.9。但是,一旦找到结果,就无法进一步搜索,因此您可以break并跳出循环。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM