×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

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.

Example

var bill = {
	name: 'I am bill',
	age: 24,
	isActive: true,
}
var marry ={
	name:'I am marry',
	age: 23,
	isActive:true,
}
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 
users.set('marry',marry)
users.set('max',max)

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

Output

Maps in JS - Output

Explanation

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

Syntax:

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

Example

Let's begin with an example:

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

for (const values of users.values()) { //line 10
	console.log(values.name);
}
console.log();

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

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)
console.log(newMap);

Output:

for...of loop in JS - Output

Explanation

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.

JavaScript Tutorial »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.