4

I was poking around some HTML5 Javascript demos and came across something I've never seen before in the syntax. Take a look at the run function and notice how the search object notation is made in the while loop. Lines of interest include 15 and 18. Can anyone explain this syntax?

function run() {
  var n = 1;
  search: while (running) {
    n += 1;
    for (var i = 2; i <= Math.sqrt(n); i += 1)
      if (n % i == 0)
       continue search;
    // found a prime!
    postMessage(n);
  }
}

(code taken from here; http://html5demos.com/js/cruncher.js)

Matt
  • 74,352
  • 26
  • 153
  • 180
Matt
  • 6,264
  • 10
  • 54
  • 82

4 Answers4

6

This is not object (literal) notation, it is defining a label.

A label can be used to give a looping construct a name. The benefits of doing this is that you can create more powerful breaks; or continues; by referencing outer loops (by their labels).

Note that how the structure of the program you referenced is a:

search: while () {
   for (;;;) {

   }
}

... and the author is using continue search; inside the for loop to continue the execution of the while loop.

As for what's happening on line 18, if (n % i == 0) is using the modulo (%) operator to get the remainder between dividing n / i, and checking whether it's 0.

Matt
  • 74,352
  • 26
  • 153
  • 180
3

search: is a label in this case that you can use to refer to this loop.

For example you can break this loop by doing break search;

m90
  • 11,434
  • 13
  • 62
  • 112
1

Since no one answered both your questions.

search: while, here search is a label which helps uniquely identify the while loop, which as mentioned, helps when using break and/or continue within nested loops.

Line 18 (n % i ===0)

Is basically looking for an odd number by applying the modulo operator.

aziz punjani
  • 25,586
  • 9
  • 47
  • 56
0

This is a label, mainly used in nested loops to break/continue a certain loop that is marked by this label. This is a standard in every programming language and not javascript specific. Read more here in section "Using Labels to Control the Flow"

http://www.tutorialspoint.com/javascript/javascript_loop_control.htm

dimcookies
  • 1,930
  • 7
  • 31
  • 37