JavaScript Tutorial ✦
Break Statement
🔁 What is the break
statement?
The break
statement is used to stop a loop right away when a certain condition is true.
🧠 Example:
Imagine you have a for
loop that counts numbers from 1 to 10.
But you want to stop the loop when the number reaches 6.
💻 Code:
for (let i = 0; i < 10; i++) {
if (i == 5) {
break; // stops the loop when i reaches 5 — till 0 to 4 the loop will work
}
}
📌 What happens here?
- The loop starts from
i = 0
- It runs again and again, increasing
i
by 1 each time - When
i
becomes5
, theif (i == 5)
condition becomes true - The
break
statement runs → 💥 loop stops immediately - It won’t go up to 10, it just stops at 5
✅ So instead of going through all the numbers from 1 to 10,
the loop ends early because of thebreak
statement.
for (let i = 0; i < =10; i++) {
if (i === 6) {
break;
}
console.log(i);
}