Dive into Javascript forEach()

Hello everyone, this time lets go through one of the popular control flow statement in programming language named as “foreach”. “foreach”, as the name suggests, it 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 lets 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. Lets check some examples and get clarified.

Example 1 :-

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

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

Example 2 :-

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 :-

// 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. Lets go through the examples.

The syntax for callback function should be like below :-

Syntax :-

function callbackfn(value, key, obj)

// As per ECMAScript
function callbackfn(value: V, index: K, map: Map)

Example 1 :-

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. Lets check some example.

Example 1 :-

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 on 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 đŸ™‚ :).

Advertisements

One thought on “Dive into Javascript forEach()

  1. Pingback: Les liens de la semaine – Édition #196 | French Coding

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s