In JavaScript, the continue
and break
statements are used to control the flow of execution within loops.
The continue
statement used to skip the current iteration of a loop and move on to the next iteration. It is often used when you only want to process certain elements within a loop.
The break
statement is used to exit a loop altogether and move on to the next statement after the loop. It is often used when you want to find the first occurrence of a certain value within an array,
Here are more examples of where continue
and break
can be used in JavaScript, along with specific examples:
continue
:- Filtering an array:
cssCopy codeconst numbers = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 !== 0) {
continue;
}
console.log(numbers[i]);
}
// Output: 2 4 6
In this example, the continue
statement skips over any elements in the numbers
array that are not even.
- Processing only a specific set of elements:
cssCopy codeconst elements = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
for (let i = 0; i < elements.length; i++) {
if (i !== 2 && i !== 4) {
continue;
}
console.log(elements[i]);
}
// Output: cherry elderberry
In this example, the continue
statement skips over all elements in the elements
array except for the third and fifth elements, which are logged to the console.
break
:- Finding the first occurrence of an element in an array:
javascriptCopy codeconst numbers = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 4) {
console.log(`Found ${numbers[i]} at index ${i}.`);
break;
}
}
// Output: Found 4 at index 3.
In this example, the break
the statement is used to exit the loop as soon as the number 4
is found in the numbers
array.
- Validating user input:
luaCopy codewhile (true) {
const input = prompt('Enter a number between 1 and 10:');
if (input >= 1 && input <= 10) {
console.log(`Valid input: ${input}`);
break;
}
console.log('Invalid input. Try again.');
}
In this example, the break
the statement is used to exit the loop when the user enters a valid number between 1 and 10. If the user enters an invalid number, the loop continues until a valid input is received.
If you have any issues or questions about it, feel free to contact me. Thank you 🌟 for reading! like, share and subscribe to my newsletter for more!