loop on array value javascript code example

Example 1: javascript loop through array

// looping through an array in javascript using our own myEach function

// Write an `Array.prototype.myEach(callback)` method that invokes a callback
// for every element in an array and returns undefined.
Array.prototype.myEach = function(callback) {
    for (let i = 0 ; i < this.length ; i ++) {
        callback(this[i]);
    }
}

let array = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];

array.myEach(function (element) {
	console.log(element); // this will print each element in the array
    // Code to do something to each element in the array
});

Example 2: iterate through array javascript

for (var key in validation_messages) {
    // skip loop if the property is from prototype
    if (!validation_messages.hasOwnProperty(key)) continue;

    var obj = validation_messages[key];
    for (var prop in obj) {
        // skip loop if the property is from prototype
        if (!obj.hasOwnProperty(prop)) continue;

        // your code
        alert(prop + " = " + obj[prop]);
    }
}