Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Dive into JavaScript forEach()

4.75/5 (3 votes)
9 Aug 2016CPOL2 min read 6.2K  
Dive into JavaScript forEach()

This time, let's go through one of the popular control flow statements in programming language named as foreach. “foreach”, as the name suggests, is a control flow statement for traversing items in one or set of collection(s). This article will cover how it works with JavaScript.

I hope everybody reading this article knows about what control flow statement is. Still let's go through a short glimpse about it.

“The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping and branching, enabling your program to conditionally execute particular blocks of code.”

It suggests flow of the control, the order in which the statements will execute in any application. Some examples are switch-case, if, if-else (decision-making statements), for, while, do-while (looping statements), return, break, continue, label (branching statements), in general.

We will go through one new control flow statement called foreach, which is supported by these languages, as per the wiki.

General Syntax

for each item in collection:
  do something to item

forEach in JavaScript, iterates upon Array or object (Map or Set) with the following syntax:

  • Array.prototype.forEach(): arrElem.forEach(callback[, args]);
  • Map.prototype.forEach(): arrElem.forEach(callback[, args]);
  • Set.prototype.forEach(): arrElem.forEach(callback[, args]);

1. Array.prototype.forEach()

The method executes the specified callback function once for every array element. Let's check some examples and get clarified.

Example 1
JavaScript
var arr = [1, 2, 3, 4, 5];
arr.forEach(function(val) {
    document.write(val + ' - ');
});

O/P: 1 – 2 – 3 – 4 – 5

Example 2
JavaScript
function getSquare(elem) {
    document.write((elem * elem) + ' - ');
}

var arr = [1, 2, 3, 4, 5];
arr.forEach(getSquare);

O/P: 1 – 4 – 9 – 16 – 25

Example 3
JavaScript
// Object which contains the callback function for forEach.
var testObj = {
    getSquare: function(elem) {
        document.write((elem * elem) + ' - ');
    }
};

var arr = [1, 2, 3, 4, 5];

// First argument is to call the getSquare function.
// Second argument 'testObj' is 'this value' present inside callback function.
arr.forEach(testObj.getSquare, testObj);

O/P: 1 – 4 – 9 – 16 – 25

2. Map.prototype.forEach()

The method executes the specified callback function once per each key/value pair in the Map object. Let's go through the examples.

The syntax for callback function should be like below:

Syntax
JavaScript
function callbackfn(value, key, obj)

// As per ECMAScript
function callbackfn(value: V, index: K, map: Map)
Example 1
JavaScript
function assignVehicle(val, key, mapObj) {
    document.write('<b>' + key + 
    '</b> has bought a new <b>'+ 
    val + '</b><br>');
}

var map = new Map();
map.set('prava', 'Fiat');
map.set('Bob', 'Harley');
map.set('Maria', 'Audi');

map.forEach(assignVehicle);

O/P
prava has bought a new Fiat
Bob has bought a new Harley
Maria has bought a new Audi

3. Set.prototype.forEach()

The method executes the specified callback function in the Set object once per each value. Let's check some example.

Example 1
JavaScript
function checkValue(val) {
    document.write(val + ' - ');
}

var setObj = new Set();
setObj.add(1);
setObj.add(2);
setObj.add('prava');
setObj.add('Maria');

setObj.forEach(checkValue);

O/P: 1 – 2 – prava – Maria

That’s it !!! We are done with the forEach statement of JavaScript. Hope you are clear about the use of forEach control statement and hope you get to know how to use it. But even though it is pretty to use and upon using, the code looks much cleaner, there are some disadvantages of using forEach, which I will cover in my upcoming blog. So, stay tuned for more details and what to use & what not.

Do you find it useful? If yes, then please like and add some comments:). Thank you and I will be happy to hear from you:):).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)