Sometimes you need more control over your loops—you might want to exit early when you find what you're looking for, or skip certain iterations based on conditions. The break and continue statements give you precise control over loop execution. Let's master these essential loop control tools!
The Break Statement
The break statement immediately exits the loop, stopping all further iterations. Control moves to the code after the loop.
Basic Break Syntax
for (let i = 0; i < 10; i++) {
if (condition) {
break; // Exit loop immediately
}
// More code
}
// Continue here after break
// Example: Stop at 5
for (let i = 0; i < 10; i++) {
console.log(i);
if (i === 5) {
break; // Exit when i is 5
}
}
console.log("Loop ended");
// Output:
// 0, 1, 2, 3, 4, 5
// Loop endedWhat happens with break:
- Loop is executing normally
breakstatement is encountered- Loop immediately terminates
- Code after the loop executes
- No more iterations happen
When to Use Break
// 1. Search - stop when found
let numbers = [5, 10, 15, 20, 25, 30];
let target = 20;
let found = false;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === target) {
found = true;
console.log("Found at index:", i);
break; // No need to continue searching
}
}
console.log("Search complete. Found:", found);
// 2. Validation - stop at first error
let userData = ["John", "john@test.com", "", "123"];
let isValid = true;
for (let field of userData) {
if (!field || field.trim() === "") {
isValid = false;
console.log("Invalid data found");
break; // Stop checking once error found
}
}
// 3. Performance - limit iterations
let count = 0;
let maxIterations = 5;
for (let i = 0; i < 1000; i++) {
count++;
if (count >= maxIterations) {
console.log("Reached maximum iterations");
break;
}
}
// 4. User interruption
let keepGoing = true;
for (let i = 0; i < 100; i++) {
console.log("Processing:", i);
// Simulate user stop
if (i > 5) {
keepGoing = false;
}
if (!keepGoing) {
console.log("User stopped the process");
break;
}
}The Continue Statement
The continue statement skips the rest of the current iteration and immediately starts the next iteration.
Basic Continue Syntax
for (let i = 0; i < 10; i++) {
if (condition) {
continue; // Skip rest of this iteration
}
// This code is skipped if continue executes
}
// Example: Skip even numbers
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // Only odd numbers reach here
}
// Output: 1, 3, 5, 7, 9What happens with continue:
- Loop iteration is executing
continuestatement is encountered- Rest of current iteration is skipped
- Loop immediately starts next iteration
- Loop continues until condition is false
When to Use Continue
// 1. Filter/Skip unwanted values
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let num of numbers) {
if (num % 2 === 0) {
continue; // Skip even numbers
}
console.log(num); // Process only odd numbers
}
// Output: 1, 3, 5, 7, 9
// 2. Skip empty/invalid data
let userInputs = ["John", "", "Jane", null, "Bob", undefined];
for (let input of userInputs) {
if (!input || input.trim() === "") {
continue; // Skip invalid entries
}
console.log("Valid input:", input);
}
// Output: "Valid input: John", "Valid input: Jane", "Valid input: Bob"
// 3. Process only specific items
let products = [
{ name: "Laptop", category: "electronics", price: 1000 },
{ name: "Shirt", category: "clothing", price: 30 },
{ name: "Phone", category: "electronics", price: 800 },
{ name: "Pants", category: "clothing", price: 50 }
];
for (let product of products) {
if (product.category !== "electronics") {
continue; // Skip non-electronics
}
console.log(`${product.name}: $${product.price}`);
}
// Output: "Laptop: $1000", "Phone: $800"
// 4. Skip certain conditions
for (let i = 1; i <= 10; i++) {
if (i % 3 === 0) {
continue; // Skip multiples of 3
}
console.log(i);
}
// Output: 1, 2, 4, 5, 7, 8, 10Break vs Continue
Different behaviors for loop control
Break (Exit Loop)
// Break: Exit entire loop
console.log("=== With Break ===");
for (let i = 0; i < 10; i++) {
console.log(i);
if (i === 5) {
break; // Stop loop
}
}
console.log("Loop ended");
// Output:
// 0, 1, 2, 3, 4, 5
// Loop ended
// (Loop stops at 5)Continue (Skip Iteration)
// Continue: Skip iteration
console.log("=== With Continue ===");
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue; // Skip 5
}
console.log(i);
}
console.log("Loop ended");
// Output:
// 0, 1, 2, 3, 4, 6, 7, 8, 9
// Loop ended
// (Skips 5, continues)Visual Comparison
// Search with break vs continue
let numbers = [5, 10, 15, 20, 25];
// Break: Stop when found
console.log("=== Break Example ===");
for (let num of numbers) {
console.log("Checking:", num);
if (num === 15) {
console.log("Found! Stopping search.");
break;
}
}
// Output:
// Checking: 5
// Checking: 10
// Checking: 15
// Found! Stopping search.
// Continue: Skip and keep going
console.log("\n=== Continue Example ===");
for (let num of numbers) {
if (num === 15) {
console.log("Skipping:", num);
continue;
}
console.log("Processing:", num);
}
// Output:
// Processing: 5
// Processing: 10
// Skipping: 15
// Processing: 20
// Processing: 25Break and Continue with Different Loops
With For Loops
// Break in for loop
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i); // 0, 1, 2
}
// Continue in for loop
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i); // 0, 1, 3, 4
}With While Loops
// Break in while loop
let count = 0;
while (count < 10) {
console.log(count);
count++;
if (count === 5) {
break; // Exit when count is 5
}
}
// Output: 0, 1, 2, 3, 4
// Continue in while loop
count = 0;
while (count < 10) {
count++;
if (count % 2 === 0) {
continue; // Skip even numbers
}
console.log(count);
}
// Output: 1, 3, 5, 7, 9With For...of Loops
let fruits = ["apple", "banana", "orange", "grape", "mango"];
// Break in for...of
for (let fruit of fruits) {
console.log(fruit);
if (fruit === "orange") {
break;
}
}
// Output: apple, banana, orange
// Continue in for...of
for (let fruit of fruits) {
if (fruit.length <= 5) {
continue; // Skip short names
}
console.log(fruit);
}
// Output: banana, orangeWith For...in Loops
let user = {
name: "John",
age: 30,
email: "john@test.com",
password: "secret",
city: "NYC"
};
// Break in for...in
for (let key in user) {
console.log(`${key}: ${user[key]}`);
if (key === "email") {
break; // Stop after email
}
}
// Continue in for...in
for (let key in user) {
if (key === "password") {
continue; // Skip password
}
console.log(`${key}: ${user[key]}`);
}
// Shows all except passwordBreak and Continue in Nested Loops
In nested loops, break and continue only affect the innermost loop they're in.
Break in Nested Loops
// Break only exits inner loop
for (let i = 0; i < 3; i++) {
console.log("Outer:", i);
for (let j = 0; j < 3; j++) {
console.log(" Inner:", j);
if (j === 1) {
break; // Only exits inner loop
}
}
}
// Output:
// Outer: 0
// Inner: 0
// Inner: 1
// Outer: 1
// Inner: 0
// Inner: 1
// Outer: 2
// Inner: 0
// Inner: 1
// To exit outer loop, use a flag
let shouldStop = false;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(`[${i}][${j}]`);
if (i === 1 && j === 1) {
shouldStop = true;
break;
}
}
if (shouldStop) break;
}
console.log("Both loops stopped");Continue in Nested Loops
// Continue only skips current iteration of inner loop
for (let i = 0; i < 3; i++) {
console.log("Outer:", i);
for (let j = 0; j < 3; j++) {
if (j === 1) {
continue; // Skip j=1 in inner loop
}
console.log(" Inner:", j);
}
}
// Output:
// Outer: 0
// Inner: 0
// Inner: 2
// Outer: 1
// Inner: 0
// Inner: 2
// Outer: 2
// Inner: 0
// Inner: 2Labeled Statements (Advanced)
// Use labels to break/continue outer loops
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(`[${i}][${j}]`);
if (i === 1 && j === 1) {
break outerLoop; // Break outer loop
}
}
}
console.log("Outer loop exited");
// Output:
// [0][0]
// [0][1]
// [0][2]
// [1][0]
// [1][1]
// Outer loop exited
// Continue with label
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) {
continue outer; // Skip to next outer iteration
}
console.log(`[${i}][${j}]`);
}
}
// Output:
// [0][0]
// [1][0]
// [2][0]Labeled statements: While powerful, labeled break and continue can make code harder to read. Use them sparingly and consider refactoring into functions instead.
Practical Patterns
Pattern 1: Early Exit (Break)
// Find first matching item
function findUser(users, id) {
for (let user of users) {
if (user.id === id) {
return user; // Found it, exit immediately
}
}
return null; // Not found
}
// Check if all conditions met
function validateAll(items) {
for (let item of items) {
if (!isValid(item)) {
return false; // One invalid, stop checking
}
}
return true; // All valid
}
function isValid(item) {
return item && item.length > 0;
}
// Process until quota reached
function processUntilQuota(items, maxItems) {
let processed = 0;
let results = [];
for (let item of items) {
results.push(processItem(item));
processed++;
if (processed >= maxItems) {
break; // Reached quota
}
}
return results;
}
function processItem(item) {
return item.toUpperCase();
}Pattern 2: Filtering (Continue)
// Process only valid items
function processValidItems(items) {
let results = [];
for (let item of items) {
// Skip invalid
if (!item || item === null) {
continue;
}
// Skip duplicates
if (results.includes(item)) {
continue;
}
// Process valid unique items
results.push(item);
}
return results;
}
// Calculate sum, skip negative
function sumPositive(numbers) {
let sum = 0;
for (let num of numbers) {
if (num < 0) {
continue; // Skip negative
}
sum += num;
}
return sum;
}
console.log(sumPositive([5, -3, 10, -1, 8])); // 23
// Build filtered array
function filterAdults(people) {
let adults = [];
for (let person of people) {
if (person.age < 18) {
continue; // Skip minors
}
adults.push(person);
}
return adults;
}Pattern 3: Search with Early Exit
// Find first occurrence
function findFirst(array, condition) {
for (let i = 0; i < array.length; i++) {
if (condition(array[i])) {
return { found: true, index: i, value: array[i] };
}
}
return { found: false };
}
let numbers = [5, 10, 15, 20, 25];
let result = findFirst(numbers, num => num > 12);
console.log(result); // { found: true, index: 2, value: 15 }
// Check if any element satisfies condition
function hasElement(array, condition) {
for (let item of array) {
if (condition(item)) {
return true; // Found one, stop searching
}
}
return false;
}
let hasLargeNumber = hasElement(numbers, num => num > 20);
console.log(hasLargeNumber); // true
// Get first N valid items
function getFirstN(array, n, condition) {
let results = [];
for (let item of array) {
if (!condition(item)) {
continue; // Skip invalid
}
results.push(item);
if (results.length >= n) {
break; // Got enough
}
}
return results;
}
let firstThreeEvens = getFirstN(
[1, 2, 3, 4, 5, 6, 7, 8],
3,
num => num % 2 === 0
);
console.log(firstThreeEvens); // [2, 4, 6]Practical Examples
Example 1: Login Validator with Retry Limit
function attemptLogin(username, password, maxAttempts = 3) {
let attempts = 0;
let isAuthenticated = false;
let correctPassword = "secret123";
while (attempts < maxAttempts) {
attempts++;
console.log(`Attempt ${attempts} of ${maxAttempts}`);
// Check username
if (!username || username.trim() === "") {
console.log("Username required");
continue; // Skip to next attempt
}
// Check password
if (password === correctPassword) {
isAuthenticated = true;
console.log("✓ Login successful!");
break; // Stop trying
} else {
console.log("✗ Incorrect password");
// Simulate new password attempt
password = attempts === 2 ? correctPassword : "wrong";
}
}
if (!isAuthenticated) {
console.log("⚠ Account locked after", maxAttempts, "failed attempts");
}
return {
success: isAuthenticated,
attempts: attempts
};
}
console.log(attemptLogin("john", "wrong"));Example 2: Data Processor with Validation
function processOrders(orders) {
let processed = [];
let skipped = [];
let stopped = false;
for (let i = 0; i < orders.length; i++) {
let order = orders[i];
// Skip invalid orders
if (!order.id) {
skipped.push({ order, reason: "Missing ID" });
continue;
}
if (!order.total || order.total <= 0) {
skipped.push({ order, reason: "Invalid total" });
continue;
}
// Stop if critical error
if (order.total > 10000) {
console.log("Critical: Order too large, stopping processing");
stopped = true;
break;
}
// Process valid order
processed.push({
id: order.id,
total: order.total,
tax: order.total * 0.08,
status: "processed"
});
}
return {
processed: processed,
skipped: skipped,
stopped: stopped,
summary: {
total: orders.length,
processed: processed.length,
skipped: skipped.length
}
};
}
let orders = [
{ id: 1, total: 50 },
{ total: 75 }, // Missing ID
{ id: 3, total: -10 }, // Invalid total
{ id: 4, total: 100 },
{ id: 5, total: 15000 } // Too large, will stop
];
console.log(processOrders(orders));Break and Continue Practice
Experiment with loop control statements
console.log() to see your output in the console above.Key Takeaways
breakexits the entire loop immediatelycontinueskips current iteration, continues to next- Use
breakfor early exit when goal is reached - Use
continueto skip invalid/unwanted items - Both work with all loop types (for, while, do-while, for...of, for...in)
- In nested loops, they only affect the innermost loop
- Use labeled statements to break/continue outer loops (use sparingly)
breakimproves performance by stopping unnecessary iterationscontinuemakes filtering logic cleaner and more readable- Can use both in same loop for complex control flow
What's Next?
Congratulations! You've completed the Loops and Iteration section. You now know how to use for loops, while loops, do-while loops, for...of, for...in, and control loop execution with break and continue. Loops are fundamental to programming—you'll use them constantly!
In the next section, we'll dive into Functions— reusable blocks of code that help you organize and structure your programs. Functions are one of the most important concepts in JavaScript, enabling you to write cleaner, more maintainable code!
💪 Practice Challenge:
Before moving on, try creating:
- A function that finds the first prime number in an array using break
- A function that sums only positive numbers using continue
- A nested loop that finds a specific value in a 2D array and breaks both loops
- A validator that stops at the first error using break
- A function that processes an array but skips duplicates using continue