JavaScript > Break and Continue

Break loop in JavaScript

How to break a loop in JavaScript?


The break statement is used to break the loop completely in middle.

    <script>
        function TestFunction() {
            var i = 0;
            do {
                if (i == 2) {
                    break;
                }
                alert(i);
                i++;
            } while (i < 5);
        }
    </script>

    <input type="button" id="btnTest" onclick="TestFunction()" value="Click me" />

Above loop executes only two times, as soon as the third iteration comes it goes into the if block and breaks the loop. User gets 0 and 1 alert only, that is shown clearly in the Demo.

 Views: 924 | Post Order: 29



Write for us