-
Notifications
You must be signed in to change notification settings - Fork 23
/
using-break.js
50 lines (43 loc) · 1.47 KB
/
using-break.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
------------------------------------------------------------------------------------
Tutorial: Breaking loops - break instruction
------------------------------------------------------------------------------------
*/
/* Loop optimization
This loop will find first even number.
Normally it would iterate through whole array, even if first number is divisible by 2.
Break ends a loop, before doing unnecessary work.
*/
const array = [0, 2, 3, 1, 7] ; //Data to search. Imagine billions of numbers
let found; //output variable
for (let i = 0; i<array.length; i++ ){ //loop through whole array
if(array[i] % 2 == 0){ //when number in array is even
found = array[i]; //assign this number to output variable
break; //end the loop
}
/*
code here wouldn't run after break
*/
}
//first instruction after break goes here
console.log("Efficient loop: " + found) ;
/* Escaping endless loop
You can use break to escape endless loop
*/
let output;
while (true) { //endless loop
// some code
const data = Math.floor(Math.random() * 100);
if(data % 2 == 0) {
output = data;
break; //escape the loop on data
}
// more code
}
//first instruction after break
console.log("Endless loop: " + output);
/*
------------------------------------------------------------------------------------
Challenge: in numbers between 0 and 200 find first, that is divisible by 2, 3, 4 and 5 at the same time
------------------------------------------------------------------------------------
*/