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)
This is not object (literal) notation, it is defining a
label.A
labelcan be used to give a looping construct a name. The benefits of doing this is that you can create more powerfulbreaks;orcontinues;by referencing outer loops (by their labels).Note that how the structure of the program you referenced is a:
… and the author is using
continue search;inside theforloop 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 dividingn / i, and checking whether it’s 0.