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 introduction of Chrome developer tools-timeline

1. Overview Users expect the web applications the...

Nginx/Httpd reverse proxy tomcat configuration tutorial

In the previous blog, we learned about the usage ...

mysql IS NULL using index case explanation

Introduction The use of is null, is not null, and...

Detailed explanation of MySQL database binlog cleanup command

Overview Today I will mainly share how to correct...

CSS achieves highly adaptive full screen

When writing my own demo, I want to use display:f...

Detailed explanation of the buffer pool in MySQL

Everyone knows that data in MySQL needs to be wri...

Implementation of vscode custom vue template

Use the vscode editor to create a vue template, s...

Is a design that complies with design specifications a good design?

In the past few years of my career, I have writte...

The difference between GB2312, GBK and UTF-8 in web page encoding

First of all, we need to understand that GB2312, ...

Detailed explanation of primary keys and transactions in MySQL

Table of contents 1. Comments on MySQL primary ke...

Using MySQL database in docker to achieve LAN access

1. Get the mysql image docker pull mysql:5.6 Note...

Linux uses join -a1 to merge two files

To merge the following two files, merge them toge...

How to solve the mysql ERROR 1045 (28000)-- Access denied for user problem

Problem description (the following discussion is ...

How to create users and manage permissions in MySQL

1. How to create a user and password 1. Enter the...