Question:
why use break in javascript loop..?
anonymous
14 years ago
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("
");
}
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...
Three answers:
Doug
14 years ago
Break allows you to terminate the loop based on conditions other than the loop count.





You could do some specific tasks that can break a loop based on a return from other functions





function foo (someArg) {

// do something

if (foobar) return true;

return false;

}



for (i=0;i<=100;i++) {

....if (!foo(someParam[i])) break;

}



in the above example, if for some reason foo() returns false, the loop will terminate. This is useful if you have a function that process some data based on parameter input as shown above. Using someParam[] as an array and using the loop count (i) as the index, we can test each parameter by calling foo().



Hmm....I think I made it more confusing now...
David
14 years ago
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 element, you don't need to check the rest so use break. -- http://jsfiddle.net/Vhx4p/
Christopher
14 years ago
Take this example:



switch($something) {

----case 1:

--------alert(1);

--------break;

----case 2:

--------alert(2);

--------break;

----case (3):

--------alert(3);

--------break;

----default:

--------alert(4);

}



If $something is 1 then it will alert 1 then break, however, if you remove break then after alerting 1, it will continue and alert 2 until 4. The break stops the switch from executing tasks it's not suppose to.



Hope this helps :)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...