Why would for loop and forEach work different?

Viewed 176

Here's the simple LeetCode function to find duplicates in the given array.

function findDuplicates(nums) {
    let hash = {}
    for (let i = 0; i < nums.length; i++) {
        if (!hash[nums[i]]) {
            hash[nums[i]] = true
        } else {
            return true
        }
    }
    
    return false
}

It works great. But what's going to happen if we switch to forEach method instead?

function findDuplicates(nums) {
    let hash = {}
    nums.forEach(el => {
        if (!hash[el]) {
            hash[el] = true
        } else {
            return true
        }
    });

    return false
}

This function will not work with the same input of [0,4,5,3,0,6]. Could you please explain why these two solutions give different results? Or just point me to the right direction.

1 Answers

Return statement is equivalent of break, for loop can be broken, foreach can't be.

Related