javascript foreach: JavaScript Array forEach() Method

javascript foreach:
The forEach() method :

Goal: Learn and control javascript foreach to minimize processing time

This method executes a provided function once for each array element.

Example 1: How to use javascript foreach on simple code.

var a = ['1', '2', '3']

a.forEach(function(element) {
console.log(element);
});
The result:
// 1
// 2
// 3

Example 2: use javascript foreach method to display liste of number

List each item in the array:

<button onclick="numbers.forEach(myFunction)">Do it</button>
<p id="demo"></p><script>
demoP = document.getElementById("demo");
var numbers = [1, 10, 6, 5];

function myFunction(item, index) {
demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + item + "<br>";
}
</script>
The result are:
index[0]: 1
index[1]: 10
index[2]: 6
index[3]: 5

Syntax

The syntax for this method is:

arr.forEach(function callback(currentValue, index, array) {
//your iterator
}[,thisArg]);

Parameters

callback
Function to execute for each element, taking three arguments:

currentValue
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The array that forEach() is being applied to.
thisArg Optional
Value to use as this(i.e reference Object) when executing callback.

Return value

undefined.

Description

forEach() executes (in ascending order ) the provided callback once for each element present in the array . It is not invoked for index properties that have been deleted or are uninitialized.

Note: forEach() does not execute the function for array elements without values.

callback is invoked with three arguments:

  • the element value
  • the element index
  • the array being traversed

Examples

Printing the contents of an array

Example 1:

function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element);
}

// Notice that index number 1 is skipped since there is no item at
// that position in the array.
[12, ,15, 19].forEach(logArrayElements);
// logs:
// a[0] = 12
// a[2] = 15
// a[3] = 19

Example 2:

calculate the sum of all the values in the array:

<button onclick="numbers.forEach(myFunction)">Do it</button>

<p>Sum of array elements: <span id="demo"></span></p>

<script>
var sum = 0;
var numbers = [1, 4, 2, 8];

function myFunction(item) {
sum += item;
demo.innerHTML = sum;
}
</script>

Example

Multiply all the values in array with a specific number:

<p>Multiply with: <input type="number" id="multiplyWith" value="10"></p>
<button onclick="numbers.forEach(myFunction)">Try it</button><p>Updated array: <span id="demo"></span></p></div>
<script>
var numbers = [5, 4, 2, 4];

function myFunction(item, index, arr) {
arr[index] = item * document.getElementById("multiplyWith").value;
demo.innerHTML = numbers;
}
</script>

Using thisArg

This example updates an object’s properties from each entry in the array:

function Counter() {
this.sum = 0;
this.count = 0;
}
Counter.prototype.add <span class="token operator">= function(array) {
array.forEach(function(entry) {
this.sum += entry;
++this.count;
}, this);
// ^---- Note
};</span>

var obj = new Counter();
obj.add([2, 5,3,9]);
obj.count
// 4
obj.sum
// 19

An object copy function

The following code creates a copy of a given object

function copy(obj) {
var copy = Object.create(Object.getPrototypeOf(obj));
var propNames = Object.getOwnPropertyNames(obj);

propNames.forEach(function(name) {
var desc = Object.getOwnPropertyDescriptor(obj, name);
Object.defineProperty(copy, name, desc);
});

return copy;
}

var obj1 = { a: 1, b: 2 };
var obj2 = copy(obj1); // obj2 looks like obj1 now

If the array is modified during iteration, other elements might be skipped.

The following example logs “one”, “two”, “four”.

var words = ['one', 'two', 'three', 'four'];
words.forEach(function(word) {
console.log(word);
if (word === 'two') {
words.shift();
}
});
// one
// two
// four

Polyfill

forEach() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard.

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {

Array.prototype.forEach = function(callback, thisArg) {

var T, k;

if (this === null) {
throw new TypeError('this is null or not defined');
}
// 1. Let O be the result of calling toObject() passing the
// |this| value as the argument.
var O = Object(this);

// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>>0;

// 4. If isCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}

// 5. If thisArg was supplied, let T be thisArg; else let
// T be undefined.
if (arguments.length > 1) {
T = thisArg;
}

// 6. Let k be 0
k = 0;

// 7. Repeat, while k < len
while (k < len) {

var kValue;

// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty
// internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {

// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];

// ii. Call the Call internal method of callback with T as
// the this value and argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}

Exercice POO