Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using for..of loop on ES6 Map

Tags:

I was reading this example of using a for.. of loop on a Map, and I was a bit confused with this syntax:

var myMap = new Map(); myMap.set(0, "zero"); myMap.set(1, "one");  for (var [key, value] of myMap) {   console.log(key + " = " + value); } 

Specifically, I don't understand the array destructuring that is happening. I understand that you can use array destructuring to do something like let [one, two] = [1, 2];, but what is happening in this example? myMap isn't an array so why is this getting the correct values?

Another question I have is why is the order key, value in the destructuring, but when you do a forEach() the order is value, key, like here:

myMap.forEach((value, key) => {   console.log(key + " = " + value); }); 
like image 261
Saad Avatar asked Dec 21 '15 06:12

Saad


2 Answers

for (var [key, value] of myMap) {     console.log(key + " = " + value); } 

is like

for (let pair of myMap) {     var [key, value] = pair;     console.log(key + " = " + value); } 

So it’s not myMap that has to be an array for the destructuring to work; rather, each of its elements has to be an array when it’s iterated over, and iterating over a map indeed produces arrays (key/value pairs).

Map#forEach’s argument order is probably for consistency with Array#forEach, which calls the function with arguments (item, index); it, in turn, probably does that because you don’t always need the index.

like image 68
Ry- Avatar answered Oct 08 '22 01:10

Ry-


Slightly off topic but as an aside:

myMap.forEach((v,k) => {}); 

is about 50% more performant than

for (var [key, value] of myMap) {  } 

so perhaps consider using Map.prototype.forEach (not to be confused with Array.prototype.forEach).

like image 36
Alexander Mills Avatar answered Oct 07 '22 23:10

Alexander Mills