JS Functions: return, break, continue & Labelled Statements
Javascriptreturn
Use return to exit a function and optionally provide a value:
function add(a, b) {
return a + b;
}
let sum = add(2, 3); // sum = 5
Once return is executed, the function stops running.
break
Use break to exit a loop (for, while, switch) early:
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i);
}
// Prints 0,1,2,3,4
continue
Use continue to skip to the next iteration of a loop:
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i);
}
// Prints 0,1,3,4
Labelled Statements
Labels let you break or continue outer loops from inside nested loops:
outerLoop:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) break outerLoop;
console.log(i, j);
}
}
// Only prints 0 0
You can use break label or continue label to control which loop to affect.