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

Login interface implemented by html+css3

Achieve results First use HTML to build a basic f...

Summary of Mysql-connector-java driver version issues

Mysql-connector-java driver version problem Since...

In-depth analysis of JDBC and MySQL temporary tablespace

background Temporary tablespaces are used to mana...

How to make if judgment in js as smooth as silk

Table of contents Preface Code Implementation Ide...

How to change the root password in a container using Docker

1. Use the following command to set the ssh passw...

MySQL5.7.27-winx64 version win10 download and installation tutorial diagram

MySQL 5.7 installation We are learning MySQL data...

Simple use of Vue bus

Simple use of Vue bus Scenario description: Compo...

The difference between html empty link href="#" and href="javascript:void(0)"

# contains a location information. The default anc...

Detailed explanation of NodeJS modularity

Table of contents 1. Introduction 2. Main text 2....

How to modify the group to which a user belongs in Linux

Modify the group to which a user belongs in Linux...

Background gradient animation effect made by css3

Achieve results Implementation Code html <h1 c...

nginx automatically generates configuration files in docker container

When a company builds Docker automated deployment...