JavaScript forEach — Powered Array for loop

Know the ins and outs of this basic JavaScript array function

Image by the author

Javascript forEach vs. for loops

let array = [1, 2, 3, 4]for (let i=0; i < array.length; i++) {
console.log(i);
}
let array = [1, 2, 3, 4]array.forEach(num => console.log(num))

Javascript array forEach method parameters

arr.forEach(callback(currentValue[, index[, array]]) {
// execute something
}[, thisArg]);
function Processor(){
this.max = 0;
this.maxAt = 0;
}
Processor.prototype.findMax = function(array){ array.forEach((num, index) => {
if (num > this.max){
this.max = num;
this.maxAt = index;
}
}, this)
}
const processor = new Processor();
processor.findMax([23, 12, 1039, 139, 2311])
console.log(processor.max) //2311
console.log(processor.maxAt) //4

Javascript forEach method — range of iteration

let array = [1, 2, 3, 4]array.forEach(num => {
array.push(num+4)
console.log(num)
})
1
2
3
4
[1, 2, 3, 4, 5, 6, 7, 8]

When to use forEach method

When not to use forEach method

let array = [23, 1, 122, 121, 87]for (let i = 0; i < array.length; i++){
if (array[i]%2 == 0){
console.log("Found an even number: " + array[i])
break;
}
}

Building our own forEach method

Array.prototype.forEachConceptual = function(callback, thisArg) {
if (!this) {
throw Error('Array.prototype.forEach called on null or undefined');
}
if (!callback || typeof callback !== 'function') {
throw Error('callback is not a function');
}
for(i=0;i<this.length;i++) {
callback(this[i], i, this);
}
}

Summary

I’m an entrepreneur, developer, author, speaker, and doer of things. I write about JavaScript, Python, AI, and programming in general.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store