Colon inside a Javascript function in a loop
I poked fun at some HTML5 Javascript demos and came across something that I had never seen in syntax before. Take a look at the trigger function and notice how the lookup denotes an object in the while loop . Interesting lines 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);
}
}
(taken from here code http://html5demos.com/js/cruncher.js )
This is not object (literal) notation, it defineslabel
.
A label
can be used to create a loop to create a name. The advantage of this is that you can create more powerful ones breaks;
or continues;
by referencing outer paths (by their labels).
Note that the structure of the program you mentioned is:
search: while () {
for (;;;) {
}
}
... and the author uses it continue search;
inside the loop for
to continue executing the while loop.
As for what happens on line 18, if (n % i == 0)
uses modulo ( %
) to get the remainder of the division n / i
and check if it's 0.
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;
Since no one answered both of your questions.
search: while
, here search
is a label that helps to uniquely identify the while loop, which, as mentioned, helps when used break
and / or continue
inside nested loops.
Line 18 (n % i ===0)
Basically searches for an odd number using the modulo operator .
It is a label mainly used in nested loops to break / continue a specific loop marked with that label. This is the standard for every programming language, not javascript. Read more here under "Using Labels for Flow Control"
http://www.tutorialspoint.com/javascript/javascript_loop_control.htm