JS Break and Continue

Break and Continue in JavaScript

In JavaScript, the break and continue statements are used to control the flow of loops. They allow us to stop or skip certain iterations based on specific conditions.

1. The Break Statement

The break statement immediately stops the loop. Once a break is reached, the loop ends, and JavaScript moves on to the next part of the code. We use this statement when we want to stop processing after meeting a specific condition.
For example
If we have a list of college subjects (like “Physics”, “Chemistry”, “Biology”, “Mathematics”, and “Computer Science”) and we want to select only one particular subject (like “Mathematics”), we can use the break statement to stop the loop once we find that subject.

JavaScript code

Note: The length property of an array returns the number of elements in that array
In this case, subjects.length would return 5 because there are five elements (or subjects) in the array.

Output

The-Break-Statement
In this example

The goal is to iterate through an array of subjects and find a specific subject, “Mathematics”. When the subject is found, a message is printed, and the loop is terminated using the break statement.

Code Breakdown:

1. Array Declaration:

let subjects = [“Physics”, “Chemistry”, “Biology”, “Mathematics”, “Computer Science”];
let chosenSubject = “Mathematics”;

• subjects is an array containing a list of subjects.
• chosenSubject is a string that holds the subject we want to find in the array.

2. For Loop:

for (let i = 0; i < subjects.length; i++) {

The loop starts with i initialized to 0 and continues until it has checked all elements in the subjects array.

3. Condition to Check for Chosen Subject:

if (subjects[i] === chosenSubject) {

This checks if the current subject in the array (subjects[i]) is equal to the chosenSubject (“Mathematics”).

4. Action for the Chosen Subject:

console.log(“Selected subject: ” + subjects[i]);
break; // Stop the loop once the subject is selected

If the current subject matches “Mathematics”, it prints the message “Selected subject: Mathematics”.
The break statement is executed, which exits the loop immediately, preventing any further iterations.

Detailed Explanation of Execution:
Detailed-Explanation-of-Execution

The loop starts with i = 0 and checks each element in the subjects array:
• For i = 0: The subject is “Physics”. This does not match “Mathematics”, so the loop continues.
• For i = 1: The subject is “Chemistry”. This does not match, so the loop continues.
• For i = 2: The subject is “Biology”. This does not match, so the loop continues.
• For i = 3: The subject is “Mathematics”. This matches the chosenSubject.
    – The message “Selected subject: Mathematics” is printed.
    – The loop breaks and no further subjects are checked.

Example 2: Stopping the Search for a Number

Let’s say you’re looking for the number 7 in a list. Once you find it, you don’t need to continue checking.

JavaScript code

let numbers = [2, 4, 6, 7, 9, 10];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === 7) {
      console.log(“Found the number: ” + numbers[i]);
    break; // Stop the loop when number 7 is found
  }
}

Output
In this example

The task is to iterate through the array numbers and find the number 7. Once the number is found, a message is printed, and the loop is terminated using the break statement.

Code Breakdown:

1. Array Declaration:

let numbers = [2, 4, 6, 7, 9, 10];

numbers is an array that contains a list of numbers.

2. For Loop:

   for (let i = 0; i < numbers.length; i++) {

This loop starts with i initialized to 0 and iterates through the numbers array until all elements are checked.

3. Condition to Check for Number 7:

   if (numbers[i] === 7) {  

This checks if the current number in the array (numbers[i]) is equal to 7.

4. Action when Number 7 is Found:

console.log(“Found the number: ” + numbers[i]);
break; // Stop the loop when number 7 is found

If the current number matches 7, it prints the message “Found the number: 7”.
The break statement is executed, which immediately stops the loop and prevents further iterations.

Detailed Explanation of Execution:

The loop begins with i = 0 and checks each element in the numbers array:
• For i = 0: The number is 2. This does not match 7, so the loop continues.
• For i = 1: The number is 4. This does not match 7, so the loop continues.
• For i = 2: The number is 6. This does not match 7, so the loop continues.
• For i = 3: The number is 7. This matches the target value.
    – The message “Found the number: 7” is printed.
    – The loop breaks, and no further numbers are checked.

2. The Continue Statement

The continue statement skips the current iteration and moves on to the next one. Unlike break, it doesn’t stop the loop entirely—it just skips over the current step.

For example: If we are looping through subjects and want to skip a specific subject (like “Environmental Science”), we can use continue to bypass it and keep looking at other subjects.

JavaScript code

let subjects = [“Physics”, “Chemistry”, “Biology”, “Mathematics”, “Environmental Science”, “Statistics”];
let unwantedSubject = “Environmental Science”;

for (let i = 0; i < subjects.length; i++) {
if (subjects[i] === unwantedSubject) {
console.log(subjects[i] + ” is not my choice, skipping it.”);
continue; // Skip the unwanted subject and move to the next
}
console.log(“Considering: ” + subjects[i]);
}

Output

In this example

The goal is to iterate through an array of subjects, skip over the unwanted subject (“Environmental Science”), and continue processing the remaining subjects. The continue statement is used to skip the unwanted subject and move on to the next iteration of the loop.

Code Breakdown:

1. Array Declaration:

let subjects = [“Physics”, “Chemistry”, “Biology”, “Mathematics”, “Environmental Science”, “Statistics”];
let unwantedSubject = “Environmental Science”;

subjects is an array containing a list of subjects.
unwantedSubject is a string that holds the subject we want to skip, “Environmental Science”.

2. For Loop:

   for (let i = 0; i < subjects.length; i++) {

The loop starts with i = 0 and iterates through each subject in the subjects array until all elements have been processed.

3. Condition to Check for Unwanted Subject:

   if (subjects[i] === unwantedSubject) {

This checks if the current subject in the array (subjects[i]) is equal to the unwantedSubject (“Environmental Science”).

4. Action when Unwanted Subject is Found:

console.log(subjects[i] + ” is not my choice, skipping it.”);
continue; // Skip the unwanted subject and move to the next

If the current subject matches “Environmental Science”, it prints a message saying the subject is not the user’s choice and skips further processing for this iteration using the continue statement. The loop then moves on to the next subject in the array without executing the next console.log statement for this iteration.

5. Output for Other Subjects:

console.log(“Considering: ” + subjects[i]);

For subjects other than “Environmental Science”, this line prints a message indicating that the user is considering the subject.

Detailed Explanation of Execution:

The loop starts with i = 0 and checks each element in the subjects array:
• For i = 0: The subject is “Physics”. Since it’s not “Environmental Science”, it prints “Considering: Physics”.
• For i = 1: The subject is “Chemistry”. It prints “Considering: Chemistry”.
• For i = 2: The subject is “Biology”. It prints “Considering: Biology”.
• For i = 3: The subject is “Mathematics”. It prints “Considering: Mathematics”.
• For i = 4: The subject is “Environmental Science”. This matches the unwantedSubject, so it prints “Environmental Science is not my choice, skipping it.” and skips further processing of this subject, moving on to the next one.
• For i = 5: The subject is “Statistics”. It prints “Considering: Statistics”.

Example 2: Skipping Odd Numbers

If you want to consider only even numbers from a list (like 1,2,3,4,5,6), you can skip the odd ones.

JavaScript code

let numbers = [1, 2, 3, 4, 5, 6];

for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 !== 0) { // If the number is odd
continue; // Skip this number and move to the next one
}
console.log(“Even number: ” + numbers[i]);
}

Output

In this example

The goal is to loop through an array of numbers and only print the even numbers, while skipping the odd numbers. The continue statement is used to skip the odd numbers and move on to the next iteration of the loop.

Code Breakdown:

1. Array Declaration:

   let numbers = [1, 2, 3, 4, 5, 6];

numbers is an array that contains a list of numbers from 1 to 6.

2. For Loop:

   for (let i = 0; i < numbers.length; i++) {

• The loop starts with i = 0 and iterates through each element in the numbers array.

3. Condition to Check for Odd Numbers:

if (numbers[i] % 2 !== 0) { // If the number is odd
continue; // Skip this number and move to the next one
}

The condition numbers[i] % 2 !== 0 checks if the current number is odd. If it is, the continue statement is executed, which skips the current iteration and moves to the next number without printing anything.

4. Action for Even Numbers:

   console.log(“Even number: ” + numbers[i]);

If the number is even (i.e., it passes the odd-number check), it prints the message “Even number: X”, where X is the even number.

Detailed Explanation of Execution:

The loop iterates through the numbers array:
• For i = 0: The number is 1, which is odd (1 % 2 !== 0), so it skips this iteration.
• For i = 1: The number is 2, which is even, so it prints “Even number: 2”.
• For i = 2: The number is 3, which is odd, so it skips this iteration.
• For i = 3: The number is 4, which is even, so it prints “Even number: 4”.
• For i = 4: The number is 5, which is odd, so it skips this iteration.
• For i = 5: The number is 6, which is even, so it prints “Even number: 6”.

Combining Break and Continue

Let’s put this all together in a real-world example. Imagine you’re registering for subjects in college. You want to select Mathematics but skip over Psychology because you’re not interested in it.

Example: Using break and continue in the same loop

let subjects = [“Physics”, “Chemistry”, “Biology”, “Mathematics”, “Psychology”, “Statistics”];
let chosenSubject = “Mathematics”;
let unwantedSubject = “Psychology”;

for (let i = 0; i < subjects.length; i++) {
if (subjects[i] === unwantedSubject) {
console.log(subjects[i] + ” is not for me, skipping it.”);
continue; // Skip the unwanted subject
}

if (subjects[i] === chosenSubject) {
console.log(“Selected subject: ” + subjects[i]);
break; // Stop once the desired subject is selected
}

console.log(“Considering: ” + subjects[i]);
}

Output

This example demonstrates how to use a loop to search for a desired subject, skip an unwanted subject, and break out of the loop once the desired subject is found. The code contains two conditions: one for skipping the unwanted subject and another for selecting the desired subject, with the continue and break statements being used appropriately.

Code Breakdown:

1. Array Declaration:

let subjects = [“Physics”, “Chemistry”, “Biology”, “Mathematics”, “Psychology”, “Statistics”];
let chosenSubject = “Mathematics”;
let unwantedSubject = “Psychology”;

subjects is an array containing the list of subjects.
chosenSubject is the subject you want to select, in this case, “Mathematics”.
unwantedSubject is the subject you want to skip, in this case, “Psychology”.

2. For Loop:

for (let i = 0; i < subjects.length; i++) {

The loop iterates through the subjects array from the first element (i = 0) to the last.

3. Condition to Skip the Unwanted Subject:

if (subjects[i] === unwantedSubject) {
console.log(subjects[i] + ” is not for me, skipping it.”);
continue; // Skip the unwanted subject
}

• If the current subject matches “Psychology”, the continue statement skips further processing for this iteration and moves to the next subject in the array.

4. Condition to Break the Loop When the Desired Subject is Found:

if (subjects[i] === chosenSubject) {
console.log(“Selected subject: ” + subjects[i]);
break; // Stop once the desired subject is selected
}

If the current subject matches “Mathematics”, it prints a message indicating that the subject is selected and exits the loop using the break statement.

5. Considering Other Subjects:

console.log(“Considering: ” + subjects[i]);

For any subject that is neither “Psychology” nor “Mathematics”, this line prints a message saying that the subject is being considered.

Detailed Explanation of Execution:

The loop iterates through the subjects array:
• For i = 0: The subject is “Physics”. Since it is neither the chosen subject nor the unwanted subject, it prints “Considering: Physics”.
• For i = 1: The subject is “Chemistry”. It prints “Considering: Chemistry”.
• For i = 2: The subject is “Biology”. It prints “Considering: Biology”.
• For i = 3: The subject is “Mathematics”. This matches the chosen subject, so it prints “Selected subject: Mathematics” and then breaks out of the loop. The remaining subjects (“Psychology” and “Statistics”) are not processed.

Summary of When to Use break and continue

Break Statement Continue Statement
Use a break statement when you want to stop the loop as soon as a condition is met. Use the continue statement when you want to skip a step but continue with the rest of the loop.
Example: When you find the book or subject you’re looking for, you stop browsing. Example: When you skip a subject that doesn’t interest you but keep browsing through other subjects.

These statements help make loops more efficient by allowing early exits or skipping unwanted iterations.

Course Video

YouTube Reference:

Practice Scenarios

Scenario 1: Skipping Negative Numbers in a Loop

Objective: Skip processing for negative numbers in an array using the continue statement.
Expected Output: The loop will iterate through an array of numbers and skip over any negative numbers.
Array: numbers = [4, -2, 7, -1, 9];

Output

Scenario 2: Breaking on a Special Character

Objective: Stop iterating through an array when a special character (*) is encountered using the break statement.
Expected Output: The loop will terminate as soon as it encounters the special character *.
Array: chars = [‘A’, ‘B’, ‘*’, ‘C’, ‘D’];

Output

Scenario 3: Find First Even Number

Objective: Iterate through an array and stop when the first even number is found using the break statement.
Expected Output: The loop will print the first even number and then stop further execution.
Array: numbers = [5, 7, 9, 2, 11, 4];

Output

Scenario 4: Continue on Odd Numbers

Objective: Process only even numbers in an array and skip odd numbers using the `continue` statement.
Expected Output: The loop will process only the even numbers, skipping any odd numbers.
Array: numbers = [1, 3, 4, 6, 7, 8];

Output

Scenario 5: Skipping a Specific Number

Objective: Skip over a specific number (like 3) in an array using the `continue` statement.
Expected Output: The loop will skip over the number 3 and continue processing the rest of the numbers.
Array: numbers = [1, 2, 3, 4, 5];

Output

Scenario 6: Search in a List of Objects

Objective: Search for a specific name in a list of objects and stop once the name is found using the break statement.
Expected Output: The loop will stop as soon as the name “Alice” is found.

let people = [
{ name: “John”, age: 25 },
{ name: “Alice”, age: 30 },
{ name: “Bob”, age: 22 }
];
for (let i = 0; i < people.length; i++) {
if (people[i].name === “Alice”) {
console.log(“Found Alice, stopping search.”);
break; // Stop when Alice is found
}
console.log(“Searching person:”, people[i].name);
}

Output

Scenario 7: Printing a Safe Range of Numbers

Objective: Create a program that prints numbers from 1 to 10 but stops printing when the number 7 is encountered (as if it’s a danger point) and skips printing the number 4 because it’s considered invalid.
Expected Output:
The loop prints numbers from 1 to 10.
The number 4 is skipped, and the loop stops entirely when it reaches 7.
Scenario Context: You are working on a simple logging system that prints a list of acceptable inputs. However:
The number 4 is not allowed (and should be skipped).
If the system encounters the number 7, it should stop immediately for safety reasons.

Output