Article Information
This Javascript tutorial contains and tries to cover following subjects:
- Brief explanation of Javascript break
- Example to Javascript break
Articles tries to provide answer to following questions and issues:
- How to break loop in Javascript
- How to stop execution of loop in Javascript?
Articles pre-requisites following information:
- General knowledge of variables in Javascript
- General knowledge of functions in Javascript
- General knowledge of HTML
Explanation of Javascript break
In this Javascript Tutorial, we will cover Javascript break subject to understand how to end an execution of loop manually. Break is a way to tell javascript stop execution and go out of loop. We had used it in Javascript SWITCH example if you recall. When break is used, next code line following loop takes control and loop ends.
To understand better, lets check syntax and how to use "break" in javascript code.
do
{
...execute some codes...
if(a condition)
{
break;
}
} while ("condition");
In above code, when our condition between for "if" block happens, "break" is executed, and regardless of while condition, loop ends itself. Flow control is passed to the new line following loop.
Example to Javascript Break
In following javascript example, we will create create a Javascript Loop and execute a code block. Our for loop executes itself 5 times according to condition which is provided to FOR. To understand break, we will put a break for 3rd cycle and stop execution.
HTML page shows result at the right pane. Our loop was being executed will "i" is smaller than "5". Our "javascript break" told javascript to stop execution when "i" reaches "3" before reaching 4.