JavaScript Control Flow
Control Flow is the order in which statements are executed in a program.
By default, JavaScript runs code from top to bottom and left to right.
Control flow statements let you change that order, based on conditions, loops or keywords.
Default Flow
Default flow runs sequentially from top to bottom:
Loops (Repetition Control Flow)
Loops lets you run code multiple times.
- for
- while
- do...while
Jump Statements
Jump statements change the flow abruptly.
- break - exits a loop or switch
- continue - skips the current loop iteration
- return - exits from a function
- throw - jumps to error handling
Example
Terminate the loop (break the loop) when the loop counter (i) is 3:
for (let i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
Try it Yourself »
Function Flow
Functions define reusable code blocks:
Example
Function to compute the product of two numbers:
function myFunction(p1, p2) {
return p1 * p2;
}
Try it Yourself »