- read

Interview: Can You Stop “forEach” in JavaScript?

fatfish 68

 
Photo by 傅甬 华 on Unsplash

Interviewer: Can you stop a forEach loop in JavaScript? This is a question I was once asked during an interview, and my initial response was, “No, I can’t do that.”

Unfortunately, my response led the interviewer to end the interview abruptly.

Frustrated with the outcome, I asked the interviewer, “Why? Is it actually possible to stop a forEach loop in JavaScript?”

Before the interviewer could answer, I took a moment to explain my understanding of why we couldn’t directly stop a forEach loop in JavaScript.

Is my answer correct?

My friends, what numbers will be output by the following code?

Will it output just one number or more?

Yes, it will output ‘0’, ‘1’, ‘2’, ‘3’.

const array = [ -3, -2, -1, 0, 1, 2, 3 ]

array.forEach((it) => {
if (it >= 0) {
console.log(it)
return // or break
}
})

That’s right! I showed this code to the interviewer, but he still believed that we could stop a forEach loop in JavaScript.

Photo by Christian Erfurt on Unsplash

Oh my God, you must be joking.

Why?

In order to convince him, I had to implement the forEach simulation again.

Array.prototype.forEach2 = function (callback, thisCtx) {
if (typeof callback !== 'function') {
throw `${callback} is not a function`
}

const length = this.length
let i = 0

while (i < length) {
if (this.hasOwnProperty(i)) {
// Note here:Each callback function will be executed once
callback.call(thisCtx, this[ i ], i, this)
}
i++
}
}

Yes, when we use ‘forEach’ to iterate through an array, the callback will be executed once for each element of the array, and there is no way we can break out of it…