JavaScript Break
The break
statement immediately stops the execution of a loop or a switch statement, transferring control to the code that follows.
Key Topics
Using break in Loops
break
can exit a loop early if a certain condition is met, saving unnecessary iterations.
for (let i = 0; i < 10; i++) {
if (i === 3) {
break;
}
console.log(i);
}
Output
> 0
> 1
> 2
Explanation: Once i equals 3, the loop stops, so only 0, 1, and 2 are printed.
Using break in switch
In a switch
statement, break
prevents execution from falling through to subsequent cases.
JavaScript Usage in DOM
Use break
to stop loops once a desired outcome is found, such as finding a matching element in a list and then updating the DOM without further searching.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Break in DOM</title>
</head>
<body>
<h1>Break Demo</h1>
<button onclick="findTarget()">Find Target</button>
<p id="result"></p>
<script>
function findTarget() {
let arr = ["Item1", "Item2", "Target", "Item3"];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === "Target") {
document.getElementById("result").textContent = "Found Target at index " + i;
break;
}
}
}
</script>
</body>
</html>
Key Takeaways
- break: Immediately stops loop or switch execution.
- Efficiency: Exit loops early when a goal is achieved.
- DOM Integration: Quickly find elements and stop searching.