-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforEach.js
More file actions
64 lines (47 loc) · 1.75 KB
/
forEach.js
File metadata and controls
64 lines (47 loc) · 1.75 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
let arrNum = [1, 2, 3, 4];
let flag = false;
arrNum.forEach((num) => {
// if (num === 2) {
if (num === 12) {
flag = true;
}
});
// You can make the flag to change its value when condition is statisifed inside
// callback fun of ForEach loop
// console.log(flag);
// !----------------------------------------------------------------------------------
/**
* code below would print 1 2 and then stop?
*
* The reason is that we are passing a callback function in our forEach function, which
* behaves just like a normal function and is applied to each element no matter if we
* return from one i.e. when element is 2 in our case.
*/
array = [1, 2, 3, 4];
array.forEach(function (element) {
console.log(element);
if (element === 2) return;
});
// Output: 1 2 3 4
// !There is no way to stop or break a forEach() loop other than by throwing an exception.
// ! If you need such behavior, the forEach() method is the wrong tool.
// !--------------------------------------------------------------------------
// *You cannot ‘break’ forEach loop
const array2 = [1, 2, 3, 4];
array2.forEach(function (element) {
console.log(element);
// if (element === 2) break;
});
// Output: Uncaught SyntaxError: Illegal break statement
// No, it won’t even run because the break instruction is not technically in a loop.
// !--------------------------------------------------------------------------
// *You cannot ‘continue’
const array3 = [1, 2, 3, 4];
array3.forEach(function (element) {
// if (element === 2) continue;
console.log(element);
});
// Output: Uncaught SyntaxError: Illegal continue statement: no surrounding iteration
// statement
// No, it won’t even run because the continue instruction is not in a loop, similar
// to the break instruction.