The break statements is used to terminate the whole current loop (e.g., for, for...of, for...in) or switch statements.
// break e.g.
const array = ['apple', 'mint', 5, 'break', [5, 58, 63]];
console.log('---ONLY STRING---')
for (let i = 0; i < array.length; i++) {
if (typeof array[i] === 'number') break;
console.log(array[i], typeof array[i]);
}
// ---ONLY STRING---
// apple string
// mint string
The return statements is used to terminate the excution of function and optionally return a value.
// return e.g.
const number = () => {
for (let i = 0; i < 10; i++ ) {
if(i === 5) {
return i;
}
console.log(i)
}
}
number()
// 0
// 1
// 2
// 3
// 4
🤔 why is 5 not logged to the console?
-> retrun just exits the function and (optionally) return the value (5 in this case), but it doesn't dispaly the value. Since the return value isn't being stored or logged anywhere in the number function, the last value printed to the console is 4.
// break & return e.g.
function example() {
for (let i = 0; i < 5; i++) {
if (i === 2) {
break; // Exits the loop when i is 2
}
console.log(i); // Output: 0, 1
}
console.log("first loop ended"); // This line will be executed
for (let i = 0; i < 5; i++) {
if (i === 3) {
return i; // Exits the function when i is 3 and returns 3
}
console.log(i); // Output: 0, 1, 2
}
console.log("second loop ended"); // This line will not be executed
}
// 0
// 1
// first loop ended
// 0
// 1
// 2
let result = example();
console.log(result); // Output: 3