Header Ads

Different Ways to Exit JavaScript Loops

Different Ways to Exit JavaScript Loops
1.Break Keyword:
let vowels = ['a','e','i','o','u'];
for (const vowel of vowels)
{
console.log(vowel);
if (vowel === 'i')
{
break;
}
}

//console output - a e i
As it can be seen when the vowel equals 'i' the condition satisfies, the break statement is next,the for of loop stops with that. 

2.Some Method:
let vowels = ['a','e','i','o','u'];
vowels.some(vowel => {
console.log(vowel);
return vowel === 'i';
});

//console output - a e i
The some method is an array method that lets you check if at least one of the elements of the given array satisfies the given condition and exits the loop.

3.Every Method:
let numbers = [2, 10, 12, 7, 16, 14];
numbers.every(number => {
console.log(number);
return (number % 2 === 0);
});

//console output - 2 10 12 7
The every method is another array method which can be used to exit an array. It function in exactly the opposite way of some method. In the above code the condition is to check if 'every' element is an even number, when the condition fails the loop is exited.

No comments:

Powered by Blogger.