-1

i wanna understand those results, why [key, value] work that way ? i dont understand how [key, value] return different in both code bellow since both are ECMA 6

let iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3

var myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');
for (var [key, value] of myMap) {
  console.log(key + ' = ' + value);
}
// 0 = zero
// 1 = one
Rhag
  • 13
  • 3
  • 2
    Possible duplicate of [Unpacking array into separate variables in JavaScript](https://stackoverflow.com/questions/3422458/unpacking-array-into-separate-variables-in-javascript) – poke Apr 01 '18 at 01:22
  • Unclear what difference you are asking about. The first `console.log` logs only values. The second logs both keys and values. –  Apr 01 '18 at 01:58

1 Answers1

0

Let's analyse the code you've written:

  • let iterable = new Map([['a', 1], ['b', 2], ['c', 3]]); creates a new Map object, which is essentialy a set of key-value pairs. Nothing too fancy here.

  • let [key, value] of iterable deconstructs the iterable object. This is a new ES6 feature that makes it possible to unpack values from arrays, or properties from objects, into distinct variables (more on this here and here).

  • finally, for (let [key, value] of iterable) {console.log(value)} simply prints the value of each map entry (hence 1, 2 and 3 in your first example).
bugs
  • 14,631
  • 5
  • 48
  • 52