Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does the break keyword actually work in JavaScript

why does the code still disregard the rest of the number after 5? I thought it was supposed to skip only number five then start with the rest of the number.

for (i = 0; i <= 10; i++) {
if (i == 5) {
    break; 
}
document.write(i + "<br />");
}
like image 693
John Micheal Avatar asked Sep 14 '26 22:09

John Micheal


2 Answers

break will quit the loop (similar to return for functions), but continue will skip the rest of the code of that iteration and go to the next iteration:

Example - log all the numbers from 1 to 6 to the console, but do not log 3, and stop logging altogether at 5 (do not log 4 or any other numbers):

for (let i = 1; i < 7; i++) {
  if (i == 3) continue;
  else if (i == 5) break;
  else console.log(i);
}
like image 146
Jack Bashford Avatar answered Sep 16 '26 12:09

Jack Bashford


break will break out of the for loop altogether, but continue will skip the rest of that iteration and move onto the next.

like image 35
helloitsjoe Avatar answered Sep 16 '26 11:09

helloitsjoe