Three things you don't know about the forEach cycle

Keywords: Java

Preface

This article is 925 words. It takes about 7 minutes to read.

Summary: three things you don't know about the forEach cycle.

He who abandons himself cannot rise, and he who strengthens himself cannot fall.

text

Do you think you really learned to use forEach?

This is my previous understanding of forEach loop: it is a for loop after general semantics, which can be broken, continue, return.

This article will show you three things you may not know about forEach.

1. Return does not stop the cycle

Do you think the following code will stop after printing 1 and 2?

array = [1, 2, 3, 4];
array.forEach(function (element) {
  console.log(element);

  if (element === 2) 
    return;
  
});
// Output: 1 2 3 4

The answer is No. the above code will print 1, 2, 3, 4 normally. If you have a Java background, you may be surprised. How is that possible?

The reason is that we passed a callback function in forEach function. The behavior of the callback function is the same as that of ordinary function. Our return operation is actually return in ordinary function. So it doesn't meet our expectation to break the forEach loop.

MDN official document:

Note: there is no way to abort or jump out of the forEach() loop except to throw an exception. If you need to abort or jump out of a loop, the forEach() method is not the tool you should use.

We rewrite the above code:

const array = [1, 2, 3, 4];
const callback = function(element) {
    console.log(element);
    
    if (element === 2) 
      return; // would this make a difference? no.
}
for (let i = 0; i < array.length; i++) {
    callback(array[i]);
}
// Output: 1 2 3 4

This is the actual execution idea of the above code. The return operation only works on the current function and will not affect the for loop naturally

2. Cannot break

Do you think the following code will be broken?

const array = [1, 2, 3, 4];
array.forEach(function(element) {
  console.log(element);
  
  if (element === 2) 
    break;
});
// Output: Uncaught SyntaxError: Illegal break statement

No, not even this line of code will not run. It directly reports an error.

So how can this code achieve the effect we originally wanted to achieve?

Just use the normal for loop:

const array = [1, 2, 3, 4];
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
  
  if (array[i] === 2) 
    break;
}
// Output: 1 2

3. Can't continue

Will the following code skip 2 print 1, 3, 4?

const array = [1, 2, 3, 4];
array.forEach(function (element) {
  if (element === 2) 
    continue;
  
  console.log(element);
});
// Output: Uncaught SyntaxError: Illegal continue statement: no surrounding iteration statement

No, just like break, this line of code will not even run after an error is reported.

How to achieve the expectation?

Or use the normal for loop:

for (let i = 0; i < array.length; i++) {
  if (array[i] === 2) 
    continue;
  console.log(array[i]);
}
// Output: 1 3 4

Translator supplement

The actual operation principle of forEach function is as follows: pseudo code is as follows:

let arr = [1, 2];
arr.forEach(function(ele) {
	console.log(ele);
}); 
// output: 1, 2
// The above code is equivalent to
function func(ele) {
  console.log(ele);
}
for (let i = 0; i < arr.length; i++) {
	func(arr[i])
}
// output: 1, 2

In fact, the implementation of forEach's polyfill is the same. Execute a for loop in the forEach function and call the callback function in the for loop.

As a result, code like the following is naturally not as expected:

let arr = [1, 2];
let sum = 0;
function add(a) {
	return a;
}
arr.forEach(async function(ele) {
  sum += await add(ele);
});
console.log(sum);
// Output: 0

Rewrite as follows:

let arr = [1, 2];
let sum = 0;
function add(a) {
	return a;
}
for (let i = 0; i < arr.length; i++) {
	sum += await add(arr[i]);
}
console.log(sum);
// Output: 3

For more articles, you can pay attention to "advanced front-end learning", reply to "666", and get a package of front-end technical books

39 original articles published, 84 praised, 90000 visitors+
Private letter follow

Posted by jasraj on Sat, 15 Feb 2020 22:23:18 -0800