Skip to content

Instantly share code, notes, and snippets.

@DevGW
Last active April 5, 2023 14:37
Show Gist options
  • Save DevGW/c42cbc958f05948f657c28abd86b4562 to your computer and use it in GitHub Desktop.
Save DevGW/c42cbc958f05948f657c28abd86b4562 to your computer and use it in GitHub Desktop.
Javascript :: continue vs. break in loops #js
// the continue keyword will cause the loop to skip to the next iteration
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log('i is', i);
}
// output: i is 1
// i is 2
// i is 4
// i is 5
// selecting only odds while loop example
let count = 5;
while (count >= 1) {
if (count % 2 === 0) {
continue;
}
console.log('count is', count);
count--;
}
// output: count is 5
// count is 3
// count is 1
// the break keyword breaks out of the loop permanently
let myGrade = 'A';
while (true) {
myGrade += '+';
if (myGrade.length === 3) {
break;
}
}
console.log(myGrade);
// caveat: don't use while(true) exept when defining a break condition!!!
// the break keyword also works in for loops
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment