9.7. Terminating a Loop With break

/*This loop executes 12 times, for values of i from 0 to 11. During the
twelfth iteration, i is 11 and the condition i > 10 evaluates to true
for the first time and execution reaches the break statement. The loop
is immediately terminated at that point.*/

for (let i = 0; i < 42; i++) {

   // rest of loop body

   if (i > 10) {
      break;
   }

}

4.43
7
Caliallye 90 points

                                    /*A while loop can be used with break to search for an element in 
an array.*/

let numbers = [ /* some numbers */ ];
let searchVal = 42;
let i = 0;

while (i &lt; numbers.length) {
   if (numbers[i] === searchVal) {
      break;
   }
   i++;
}

if (i &lt; numbers.length) {
   console.log(&quot;The value&quot;, searchVal, &quot;was located at index&quot;, i);
} else {
   console.log(&quot;The value&quot;, searchVal, &quot;is not in the array.&quot;);
}

/*Notice that we use a while loop in this example, rather than a 
for loop. This is because our loop variable, i, is used outside the 
loop. When we use a for loop in the way we have been, the loop 
variable exists only within the loop.*/

4.43 (7 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source