JS interview question: Can forEach jump out of the loop?

JS interview question: Can forEach jump out of the loop?

When I was asked this question, I was ignorant and my mind went blank. Of course, I didn't answer it correctly. I have always had a wrong understanding of forEach. Since it is much simpler than the original for loop, I once thought that it was a syntactic sugar created for the convenience of writing. It is also often used in business, but I have never considered the problems with this approach.

forEach usage instructions

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=example

arr.forEach(function callback(currentValue, index, array) {
    //your iterator
}[, thisArg]);
  • currentValue --- The element currently being processed
  • index --- The index of the currently processed element
  • array ---the array to which forEach is applied

There is a tip about the usage of break and return in forEach. The original text is as follows:

There is no way to stop or break a forEach()loop other than by throwing an exception. If you need such behavior, theforEach()method is the wrong tool. Use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can useevery() or
some() instead. If available, the new methods find() or findIndex() can be used for early termination upon true predicates as well.

This means that it is wrong to use break and return in forEach. If you want to use break or return, please use every or some function.

So back to the title, first of all, forEach cannot use any means to jump out of the loop, why? We know that forEach receives a function, which generally has two parameters, the first is the current element of the loop, and the second is the subscript corresponding to the element. Let's implement it manually:

Array.prototype.myForEach = function (fn) {
    for (let i = 0; i < this.length; i++) {
        fn(this[i], i, this);
    }
}

I have no way of knowing whether forEach is really implemented this way, but the simple pseudocode above does meet the characteristics of forEach, and it is also obvious that you cannot jump out of the loop because you have no way to operate the real for loop body.

Later, after consulting the documents, I found that the official definition of forEach was not the syntactic sugar I thought it was. Its standard statement is that forEach executes the function you provide once for each array element. At this point my thoughts gradually became clear, and the official documentation also has this paragraph:

There is no way to stop or break out of the loop other than throwing an exception. If you need this behavior, the forEach() method is the wrong tool.

Use throwing exception to jump out of foreach loop

let arr = [0, 1, "stop", 3, 4];
try {
    arr.forEach(element => {
        if (element === "stop") {
            throw new Error("forEachBreak");
        }
        console.log(element); // Output 0 1 and nothing after that });
} catch (e) {
    console.log(e.message); // forEachBreak
};

Of course, when using try-catch wrapper, when the loop body is too large, the performance will decrease, which is unavoidable. Therefore, throwing an exception is not a silver bullet to solve the forEach problem. Let's go back to the pseudo code written at the beginning. We will optimize it and add the judgment of the passed function to the real for loop:

Array.prototype.forEach = function (fn) {
    for (let i = 0; i < this.length; i++) {
        let ret = fn(this[i], i, this);
        if (typeof ret !== "undefined" && (ret == null || ret == false)) break;
    }
}

In this way, you can naturally jump out of the loop according to the return value:

let arr = [0, 1, "stop", 3, 4];

arr.forEach(element => {
    if (element === 'stop') return false
    console.log(element); // Output 0 1 and nothing after that });

console.log('return means continue:');
arr.forEach(element => {
    if (element === 'stop') return
    console.log(element); // 0 1 3 4
});

The document also mentions that forEach requires a synchronous function, which means that unexpected results may occur when using asynchronous functions or Promises as callbacks, so forEach should be used with caution or not at all. Of course, this does not mean that we should always use simple for loops to complete everything in project development. We can use for..of.. when traversing arrays and for..in.. when traversing objects. The official also lists some other tool functions under the forEach document:

Array.prototype.find()
Array.prototype.findIndex()
Array.prototype.map()
Array.prototype.filter()
Array.prototype.every()
Array.prototype.some()

Depending on different business scenarios, choose to use the corresponding tool function to handle business logic more effectively. As for forEach, I think I will just forget about it from now on.

Summarize

This is the end of this article about the JS interview question whether forEach can jump out of the loop. For more relevant content about JS forEach jumping out of the loop, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example of how to exit the loop in Array.forEach in js
  • JS forEach jumps out of the loop 2 ways to implement
  • Summary of examples of using forEach, for in, and for of loops in js
  • Detailed usage of js array forEach instance

<<:  A Deep Dive into the MySQL InnoDB Storage Engine

>>:  Solve the problem of being unable to ping the external network after installing Centos7 in VMware

Recommend

Detailed graphic and text instructions for installing MySQL 5.7.20 on Mac OS

Installing MySQL 5.7 from TAR.GZ on Mac OS X Comp...

Detailed explanation of using echarts map in angular

Table of contents Initialization of echart app-ba...

Detailed explanation of concat related functions in MySQL

1. concat() function Function: Concatenate multip...

Detailed explanation of Docker Secret management and use

1. What is Docker Secret 1. Scenario display We k...

Linux IO multiplexing epoll network programming

Preface This chapter uses basic Linux functions a...

Two ways to implement HTML to randomly drag content positions

Test: Chrome v80.0.3987.122 is normal There are t...

JavaScript closure details

Table of contents 1. What is a closure? 2. The ro...

About Vue virtual dom problem

Table of contents 1. What is virtual dom? 2. Why ...

Vue makes div height draggable

This article shares the specific code of Vue to r...

Detailed explanation of JavaScript timers

Table of contents Brief Introduction setInterval ...

MySQL 5.7.10 installation and configuration tutorial under Windows

MySQL provides two different versions for differe...

How to filter out duplicate data when inserting large amounts of data into MySQL

Table of contents 1. Discover the problem 2. Dele...

Teach you how to get the pointer position in javascript

The method of obtaining the position of the point...