1/*A while loop can be used with break to search for an element in
2an array.*/
3
4let numbers = [ /* some numbers */ ];
5let searchVal = 42;
6let i = 0;
7
8while (i < numbers.length) {
9 if (numbers[i] === searchVal) {
10 break;
11 }
12 i++;
13}
14
15if (i < numbers.length) {
16 console.log("The value", searchVal, "was located at index", i);
17} else {
18 console.log("The value", searchVal, "is not in the array.");
19}
20
21/*Notice that we use a while loop in this example, rather than a
22for loop. This is because our loop variable, i, is used outside the
23loop. When we use a for loop in the way we have been, the loop
24variable exists only within the loop.*/
1/*This loop executes 12 times, for values of i from 0 to 11. During the
2twelfth iteration, i is 11 and the condition i > 10 evaluates to true
3for the first time and execution reaches the break statement. The loop
4is immediately terminated at that point.*/
5
6for (let i = 0; i < 42; i++) {
7
8 // rest of loop body
9
10 if (i > 10) {
11 break;
12 }
13
14}