Home » JavaScript Tutorial

maps and for...of loops | Javascript

In this tutorial, we are going to learn about maps and for…of loops in JavaScript with Examples.
Submitted by Himanshu Bhatt, on September 09, 2018

1) map

Let’s start with the maps, we normally use them when working with NoSQL databases like MongoDB or Firebase. It stores key-value pair.


var bill = {
	name: 'I am bill',
	age: 24,
	isActive: true,
var marry ={
	name:'I am marry',
	age: 23,
var max = {
	name: 'I am max',
	age: 29,
	isActive: false,

let users = newMap()

console.log(typeof users) //line 1
console.log('\n',users); //line 2
users.set('bill',bill)	//line 3 

console.log(`\nsize of map 'users': ${users.size}`);  //line 4
console.log('\n',users.get('max')); //line 5
console.log('\n',users.keys());	//line 6
console.log('\n',users.values(),'\n');	//line 7


Maps in JS - Output


We created three objects, bill, marry and max. Each contains three properties: name (name of the user), age (age of user) and isActive (active status true or false). Then we created an object of Map class using users = new Map() (Note: We will not discuss objects and class here in this article as it is out the scope of the article).

That's why we consoled out typeof users in line 1 which returns an object and that is obvious. In line 2 we passed our users object which outputs an empty map. (Please ignore the '\n' escape sequence I just used it to make the output more readable)

In line 3, we populated the users with key-value fashion that is we provide value for each key, for this we used set() method we take the first argument as key and second as the value. In the above example, I used bill as in line 3 as users.set('bill', bill) where I could write it billy, ball or whatever I like. Notice here, we used a string (bill) as key and the object (bill) as value though it can be vice versa it will not make any much sense. There is a property of map object that is a size which guesses the size (number of key-value pairs) of that object. As depicted in line 4.

As an analogy to the array, we can access to arrays by using square brackets [] similarly, we can access to the users using get() method as in line 5, it needs a key as its parameter and it will return the value corresponding to it. Similar to get() method we have keys() and values() which returns the list of all the keys and the values respectively, as shown in the outputs of line 4 & 5.

In last two outputs, you might notice that it says MapIterator it is something we can iterate over it or loop through it. Let’s see it next section:

2) for...of loop


    for (const iterator of object) {
        ...OUR CODE...

Let's begin with an example:

console.log('\n',users,'\n') //line 8
for (const keys ofusers.keys()) {  //line 9

for (const values of users.values()) { //line 10

for (const [key, value] of users.entries()) { //line 11
	console.log(`${key} = ${value.name}`);

users.forEach((value, key) =>console.log(`${key} = ${value.name}`) ) // line 12

var arrayOfArray = [['one',1],['two',2],['three',3]] //line 13
var newMap = newMap(arrayOfArray)


for...of loop in JS - Output


In Line 8, we console out user (Note: '\n' escape sequence are only for beautiful output same with empty console log command) and in output, we will get a complete map. See each key is pointing to its value (object). In line 9 and 10, we used a for...of loop which basically iterates in inerrable in our case they are keys and values thus we used users.keys() and users.values() to iterate (loop) through keys and values respectively.

Now, what if I want a key-value pair or I want to loop through key-value pairs so in that case, we will use array [key, value] passed in users.entries(). Remember that we do not iterate it in users but used method entries() which returns key-value pair. So for a pair, we pass an array in a for...of loop.

Since we are talking about MapIterators it can also be looped through forEach() as in line 12 we used user.forEach() with an arrow function simply to console log an output. But the thing to notice here in arrow function we passed value-key pair instead of a key-value pair, and it is the way forEach works for Map, doing the reverse of it will not result in the desiredway.

There is one more thing we can do with Maps using arrays, this is what we did after line 13. We had an array of arrays where each subarray contains 2 elements only as key and value, so we created an object newMap (the similar way we created users map) but we passed arrayOfArray array of arrays having key-value it will map itself to each key to its value.

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.