Unraveling the Peculiar Pitfall in JavaScript – forEach Loop Fails to Exit with return!

What happened

While practicing LeetCode problems, I encountered an issue related to JavaScript and decided to make a record to avoid forgetting it.

The specific problem ➡ Zyrastor-LeetCode#1338

Here’s the context with a portion of the code:

There is a section of the code where I perform a forEach loop on an array (Object.values returns an array).

    //2.order by values
    var k = Object.values(dict);
    k.sort();
    k = k.reverse();
    
    //3.find result
    var res = 0;
    k.forEach(function(s){
        if (s>mid)
        {                
            return res == 0 ? 1 : res+1;
        }
        else if (s<mid)
        {
            mid -= s;
            res +=1;
        }
        else    //s == mid
        {
            return res+1;
        }
    });
    return res;

I wanted to explain that logically everything seems fine, so why does it keep failing when I submit it?

Upon further examination, it appears that it returns only at line 23.

What could be happening!? The if-else statements above should have a return, right?

It’s indeed quite mysterious, so let’s try a simple function to investigate.

function test() {
    arr = ['apple','pineapple','orange','lemon'];

    arr.forEach(function(s){
        if(s=='apple')
        {
            return 'Doctors don't like this fruit';
        }
        else if(s=='orange')
        {
            return 'Vitamin C';
        }
    });
    return 'Else';
}
k = test();

Like the title suggests, it didn’t return what we expected. (return after s==’apple’)

Instead, it returned “Else” !!!

Let’s now look into the JavaScript technical documentation and find the following section:

What!!!?? So, the only way to terminate the loop is by throwing an exception? It’s completely different from the regular foreach loop in C#.

So, let’s go back to using the basic for loop for the initial problem

//2.order by values
    var k = Object.values(dict);
    k.sort();
    k = k.reverse();
    
    //3.find result
    var res = 0;
    for (let i = 0; i < k.length; i++) {
        const s = k[i];
        
        if (s>mid)
        {                
            return res == 0 ? 1 : res+1;
        }
        else if (s<mid)
        {
            mid -= s;
            res +=1;
        }
        else    //s == mid
        {
            return res+1;
        }
    }
    
    return res;

Now we can get the answer we expected.


Conclusion

In conclusion, if you need to return in an iteration of array in JavaScript, you should use for loop instead of using forEach function !!

🧡You can support me by clicking some ad, Thanks a lot

If you got any problem about the explanation, please feel free to let me know

Reference

Random post

Leave a Reply

Your email address will not be published. Required fields are marked *