- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Break and Continue Statements
When working with loops in JavaScript, you often need more granular control over how the loop behaves. While a loop's condition usually determines when it stops, there are times you need to jump out of a loop early or skip specific items based on logic inside the loop body. This is where the break and continue statements come in.
Break Statement
The break statement acts as an "emergency exit" for your loops. When the JavaScript engine encounters a break, it immediately stops the loop's execution and moves to the first line of code following the loop's closing curly brace.
Syntax:
for (let i = 0; i < 10; i++) {
// Code block
if (/* some condition */) {
break; // Exit the loop entirely if the condition is true
}
}
// Code execution resumes here after the break
break statement to improve performance. For example, if you are searching for a single item in a list of 10,000, you should break as soon as you find it to avoid 9,999 unnecessary iterations.
The break statement can be used with for, while, and do...while loops, as well as within switch statements.
Why it is Used:
Conditional Exit: It allows you to terminate a loop based on dynamic data or user input that wasn't part of the original loop condition.
Example: Finding a specific user
Imagine you are searching through an array of usernames. Once you find the match, there is no reason to keep looking through the rest of the list.
const users = ["Alice", "Bob", "Charlie", "David", "Eve"];
const searchFor = "Charlie";
for (let i = 0; i < users.length; i++) {
console.log("Checking: " + users[i]);
if (users[i] === searchFor) {
console.log("Match found!");
break; // We found Charlie, so we stop the loop here
}
}
break only exits the inner-most loop. If you have a loop inside another loop, a break in the inner loop will not stop the outer loop.
Continue Statement
The continue statement is less drastic than break. Instead of quitting the entire loop, it simply skips the current iteration and jumps straight to the next one. Think of it as saying, "I'm done with this specific item; let's move on to the next."
Syntax:
for (let i = 0; i < 10; i++) {
// Code here runs for every iteration
if (/* some condition */) {
continue; // Skip the rest of the code in this block and move to i++
}
// This code is skipped only if the condition above is true
console.log("This will not run if continue was triggered");
}
continue to avoid "Arrow Code" (deeply nested if-statements). By skipping invalid data early, you can keep your main logic at a shallower indentation level.
The continue statement is compatible with for, while, and do...while loops.
Why it is Used:
Skip Current Iteration: It is perfect for filtering out unwanted data points while still processing the rest of the collection.
Example: Filtering Odd Numbers
for (let i = 1; i <= 10; i++) {
// If the number is even, skip the log and go to the next number
if (i % 2 === 0) {
continue;
}
console.log("Odd number found: " + i);
}
Real-World Example: Data Validation
Suppose you are processing a list of transactions, but some entries are missing an amount. You want to skip the broken ones and process the rest.
const transactions = [100, -20, null, 50, undefined, 10];
for (let amount of transactions) {
if (amount === null || amount === undefined) {
console.warn("Skipping invalid transaction record.");
continue;
}
console.log("Processing transaction: $" + amount);
}
continue inside while loops. If your incrementer (like i++) is located at the bottom of the loop, continue will skip it, potentially creating an infinite loop.
Summary
- The break statement completely stops the loop and moves control to the code after the loop.
- The continue statement "skips a turn," stopping the current iteration and immediately starting the next one.
- Break is ideal for stopping a search or an infinite loop when a condition is met.
- Continue is ideal for filtering out specific items or handling errors without stopping the entire process.
- Both statements help make your loops more efficient and your logic cleaner by controlling the flow of execution.