बिना लेबल के तोड़ें
ब्रेक स्टेटमेंट का उपयोग लूप से जल्दी बाहर निकलने के लिए किया जाता है, जो संलग्न घुंघराले ब्रेसिज़ को तोड़ता है। ब्रेक स्टेटमेंट लूप से बाहर निकलता है।
उदाहरण
आइए लेबल का उपयोग किए बिना जावास्क्रिप्ट में ब्रेक स्टेटमेंट का एक उदाहरण देखें -
लाइव डेमो
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html> लेबल के साथ तोड़ें
लेबल का उपयोग किसी प्रोग्राम के प्रवाह को नियंत्रित करने के लिए किया जाता है यानी मान लीजिए कि इसे नेस्टेड लूप में उपयोग करके आंतरिक या बाहरी लूप पर जाने के लिए उपयोग किया जाता है। आप ब्रेक स्टेटमेंट के साथ प्रवाह को नियंत्रित करने के लिए लेबल का उपयोग करने के लिए निम्न कोड चलाने का प्रयास कर सकते हैं -
उदाहरण
लाइव डेमो
<html>
<body>
<script>
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>