Is the break keyword in Javascript just to exit loops?

One of my friends is teaching a programming class with Javascript, and one of his purposes was to create a game with many guesses. This was an example of its implementation:

funProgram: for(;;) {
  numberGuesser: {
    var num = (Math.random() * 100) | 0;
    var guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", 0);
    var guesses = 1;
    guess: for(;;) {
      higher: {
        lower: {
          if(guess === num) break guess;
          if(guess > num) break lower;
          guess = +prompt("Too low. Try again.", 0);
          break higher;
        }
        guess = +prompt("Too high. Try again.", 0);
      }
      guesses++;
    }
    alert("You got it in " + guesses + " guesses! The number is " + num);
  }
  var again = prompt("Do you want to guess again (y/n)?", "y") === "y";
  if(!again) break funProgram;
}

He told me that it is good practice to label your code and wrap blocks around it so you can easily see what each section does. He also said that marked breaks and continue to be much easier to read than unlabeled, because you can know exactly what you're coming out of. I have never seen code templates like this, so I'm not sure if this is true.

Javascript - , , , , . , break . higher lower , , , . ? -, . break?

+5
4

( ). , , "", , "" , . , , . (, IMHO, BASIC/GOTO, -).

: , BASIC; , "" ( ), , BASIC/VB [ ])

break , , , , . , . :

for (;;){ // "for a"
  for(;;){ // "for b"
    break; // breaks "for b"
  }
}

break ( " b" ) . :

myblock: {
  for(;;){
    for(;;){
      break mybock; // breaks label "myblock"
    }
  }
}

break , . , :

function myblock(){
  for(;;){
    for(;;){
      return; // exits function "myblock"
    }
  }
}

return , , break myblock.


, :

var again = true;
while (again){
    var num = (new Date()).getMilliseconds() % 100,
        guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", "1"),
        guesses = 1;
    while (num !== guess){
        guesses++;
        guess = +prompt((guess < num ? "Too low." : "Too high.") + " Try again.", guess);
    }
    alert("You got it in " + guesses + " guesses! The number is " + num);
    again = prompt("Do you want to guess again? (y/n)", "y") == "y";
}
+3

label break javascript. , , , block , . Mozilla , :

JavaScript, . , , .

:

  • break for, while case, blocks.

  • break , return.

+1

MDN ( ):

break , . break . block ; .

, , , , .

0

break , goto . : switch, .

, , , for(;;).

Check out this article here for more information: http://james.padolsey.com/javascript/labelled-blocks-useful/

0
source

All Articles