Answers for "9.7. Terminating a Loop With break"

0

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;
   }

}
Posted by: Guest on June-18-2021
0

9.7. Terminating a Loop With break

/*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 < numbers.length) {
   if (numbers[i] === searchVal) {
      break;
   }
   i++;
}

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

/*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.*/
Posted by: Guest on June-18-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language