JavaScript break Statement In Hindi


break  का use  current loop (for Loop , for in Loop , for of Loop , while Loop , do while Loop या switch  loop ) execution को terminate करता है।

JavaScript break Syntax

break [label];

break भी continue statement की तरह एक Optional parameter accept करता है , जो current या parent loop को identify करता है जिसका current execution terminate करना हो।

JavaScript break Example

File : for_break.html

Copy Fullscreen Close Fullscreen Run
<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8">
    <title>JavaScript break Statement </title>
 </head>
 <body>
   <script>
      let x;
      for(x=1; x <= 5 ; x++)
      {
        if(x==3)
        {
          break;
        } 
        document.write(`${x} <br>`);
      }
    </script>
 </body>
</html>
Output
1
2

Example में आप देख सकते हैं कि x की value 3 होते ही loop terminate हो गया।

break statement हमेशा referenced label के अंदर ही होना चाहिए।

JavaScript break with labeled statement

File : break2.html

Copy Fullscreen Close Fullscreen Run
<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8">
    <title>JavaScript break with labeled Statement </title>
 </head>
 <body>
   <script>
      let x;
      outer_loop : for(x=1; x <= 5 ; x++)
      {
        let y;
        inner_loop :for(y=1; y <= x; y++)
        {
          if(x == 3)
            break outer_loop;
          document.write(`Inner Loop Value : ${y} <br>`);
        }
        document.write(`Outer Loop Value : ${x} <br>`);
      }
    </script>
 </body>
</html>
Output
Inner Loop Value : 1
Outer Loop Value : 1
Inner Loop Value : 1
Inner Loop Value : 2
Outer Loop Value : 2

Example में आप देख सकते हैं की break के बाद label , parent loop को identify कर रहा है।


label का नाम किसी दूसरे independent loop को identify कर रहे label नहीं दे सकते हैं।नीचे कुछ valid या invalid syntax दिए गए हैं।

Copy Fullscreen Close Fullscreen
/* It will work*/
outer_block: {
inner_block: {
document.write('inner block');
break outer_block; /* breaks out of both inner_block and outer_block */
document.write('inner block 2'); /* skip */
}
document.write('outer block'); /* skip */
}

/*It generates error : Uncaught SyntaxError: label not found */
label1 : {
document.write('label 1');
break label2;
}

label2 :{
document.write('label 2');
}

Hey ! I'm Rahul founder of learnhindituts.com. Working in IT industry more than 4.5 years. I love to talk about programming as well as writing technical tutorials and blogs that can help to others .... keep learning :)

Get connected with me - LinkedIn Twitter Instagram Facebook