Common JavaScript Manual/Break, continue, labels

From Wikibooks, open books for an open world
< Common JavaScript Manual
Jump to: navigation, search

Break[edit]

Break statement can interrupt the cycle. For example.

str = "";
i = 0;
j = 100;
while(true){
  i++;
  j--;
  if(j==i)break;
  str = str + i + ':' + j + ',';
}

This code makes string with list of pairs of numbers while they are not equal.

Continue[edit]

Continue statement makes the transition to the next iteration of the loop.

arr = [0,2,4,5,6,1,24,36,12,531,42,49,81];
for(i=0;i<arr.length;i++){
  if((Math.sqrt(arr[i])%1) > 0)continue;
  print(arr[i])
}

This script output numbers from array which square roots is integer.

Labels[edit]

Labels help use break and continue in nested loops.

glob:for(i=0;i<10;i++){
  for(j=0;j<10;j++){
    if(i==j)continue glob;
    print(i*10 + j)
  }
}

Do .. While and For .. in loops · Logic and Comparison operators