aboutsummaryrefslogtreecommitdiff
path: root/files/ar/web/javascript/reference/global_objects/map/index.html
blob: ba5bc938043409066846377c57125d2f829e9cb9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
---
title: Map
slug: Web/JavaScript/Reference/Global_Objects/Map
translation_of: Web/JavaScript/Reference/Global_Objects/Map
---
<div>{{JSRef}}</div>

<p><span class="seoSummary">The <strong><code>Map</code></strong> object holds key-value pairs and remembers the original insertion order of the keys.</span> Any value (both objects and {{glossary("Primitive", "primitive values")}}) may be used as either a key or a value.</p>

<h2 id="Description">Description</h2>

<p>A <code>Map</code> object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of <code>[<var>key</var>, <var>value</var>]</code> for each iteration.</p>

<h3 id="Key_equality">Key equality</h3>

<ul>
 <li>Key equality is based on the <a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality"><code>sameValueZero</code></a> algorithm.</li>
 <li>{{jsxref("NaN")}} is considered the same as <code>NaN</code> (even though <code>NaN !== NaN</code>) and all other values are considered equal according to the semantics of the <code>===</code> operator.</li>
 <li>In the current ECMAScript specification, <code>-0</code> and <code>+0</code> are considered equal, although this was not so in earlier drafts. See <em>"Value equality for -0 and 0"</em> in the <a href="#Browser_compatibility">Browser compatibility</a> table for details.</li>
</ul>

<h3 id="Objects_vs._Maps">Objects vs. Maps</h3>

<p>{{jsxref("Object")}} is similar to <code>Map</code>—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), <code>Object</code>s have been used as <code>Map</code>s historically.</p>

<p>However, there are important differences that make <code>Map</code> preferable in certain cases:</p>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="row"></th>
   <th scope="col">Map</th>
   <th scope="col">Object</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <th scope="row">Accidental Keys</th>
   <td>A <code>Map</code> does not contain any keys by default. It only contains what is explicitly put into it.</td>
   <td>
    <p>An <code>Object</code> has a prototype, so it contains default keys that could collide with your own keys if you're not careful.</p>

    <div class="blockIndicator note">
    <p><strong>Note:</strong> As of ES5, this can be bypassed by using {{jsxref("Object.create", "Object.create(null)")}}, but this is seldom done.</p>
    </div>
   </td>
  </tr>
  <tr>
   <th scope="row">Key Types</th>
   <td>A <code>Map</code>'s keys can be any value (including functions, objects, or any primitive).</td>
   <td>The keys of an <code>Object</code> must be either a {{jsxref("String")}} or a {{jsxref("Symbol")}}.</td>
  </tr>
  <tr>
   <th scope="row">Key Order</th>
   <td>
    <p>The keys in <code>Map</code> are ordered. Thus, when iterating over it, a <code>Map</code> object returns keys in order of insertion.</p>
   </td>
   <td>
    <p>The keys of an <code>Object</code> are not ordered.</p>

    <div class="blockIndicator note">
    <p><strong>Note:</strong> Since ECMAScript 2015, objects <em>do</em> preserve creation order for string and <code>Symbol</code> keys. In JavaScript engines that comply with the ECMAScript 2015 spec, iterating over an object with only string keys will yield the keys in order of insertion.</p>
    </div>
   </td>
  </tr>
  <tr>
   <th scope="row">Size</th>
   <td>The number of items in a <code>Map</code> is easily retrieved from its {{jsxref("Map.prototype.size", "size")}} property.</td>
   <td>The number of items in an <code>Object</code> must be determined manually.</td>
  </tr>
  <tr>
   <th scope="row">Iteration</th>
   <td>A <code>Map</code> is an <a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a>, so it can be directly iterated.</td>
   <td>Iterating over an <code>Object</code> requires obtaining its keys in some fashion and iterating over them.</td>
  </tr>
  <tr>
   <th scope="row">Performance</th>
   <td>
    <p>Performs better in scenarios involving frequent additions and removals of key-value pairs.</p>
   </td>
   <td>
    <p>Not optimized for frequent additions and removals of key-value pairs.</p>
   </td>
  </tr>
 </tbody>
</table>

<h3 id="Setting_object_properties">Setting object properties</h3>

<p>Setting Object properties works for Map objects as well, and can cause considerable confusion.</p>

<p>Therefore, this appears to work in a way:</p>

<pre class="syntaxbox example-bad brush js notranslate">let wrongMap = new Map()
wrongMap['bla'] = 'blaa'
wrongMap['bla2'] = 'blaaa2'

console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }
</pre>

<p>But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of 'bla' is not stored in the Map for queries. Othere operations on the data fail:</p>

<pre class="syntaxbox example-bad brush js notranslate">wrongMap.has('bla')    // false
wrongMap.delete('bla') // false
console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }</pre>

<p>The correct usage for storing data in the Map is through the set(key, value) method.</p>

<pre class="syntaxbox brush js example-good notranslate">let contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
contacts.has('Jessie') // true
contacts.get('Hilary') // undefined
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete('Raymond') // false
contacts.delete('Jessie') // true
console.log(contacts.size) // 1

</pre>

<h2 id="Constructor">Constructor</h2>

<dl>
 <dt>{{jsxref("Map/Map", "Map()")}}</dt>
 <dd>Creates a new <code>Map</code> object.</dd>
</dl>

<h2 id="Static_properties">Static properties</h2>

<dl>
 <dt>{{jsxref("Map.@@species", "get Map[@@species]")}}</dt>
 <dd>The constructor function that is used to create derived objects.</dd>
</dl>

<h2 id="Instance_properties">Instance properties</h2>

<dl>
 <dt>{{jsxref("Map.prototype.size")}}</dt>
 <dd>Returns the number of key/value pairs in the <code>Map</code> object.</dd>
</dl>

<h2 id="Instance_methods">Instance methods</h2>

<dl>
 <dt>{{jsxref("Map.prototype.clear()")}}</dt>
 <dd>Removes all key-value pairs from the <code>Map</code> object.</dd>
 <dt>{{jsxref("Map.delete", "Map.prototype.delete(<var>key</var>)")}}</dt>
 <dd>Returns <code>true</code> if an element in the <code>Map</code> object existed and has been removed, or <code>false</code> if the element does not exist. <code>Map.prototype.has(<var>key</var>)</code> will return <code>false</code> afterwards.</dd>
 <dt>{{jsxref("Map.prototype.entries()")}}</dt>
 <dd>Returns a new <code>Iterator</code> object that contains <strong>an array of <code>[<var>key</var>, <var>value</var>]</code></strong> for each element in the <code>Map</code> object in insertion order.</dd>
 <dt>{{jsxref("Map.forEach", "Map.prototype.forEach(<var>callbackFn</var>[, <var>thisArg</var>])")}}</dt>
 <dd>Calls <code><var>callbackFn</var></code> once for each key-value pair present in the <code>Map</code> object, in insertion order. If a <code><var>thisArg</var></code> parameter is provided to <code>forEach</code>, it will be used as the <code>this</code> value for each callback.</dd>
 <dt>{{jsxref("Map.get", "Map.prototype.get(<var>key</var>)")}}</dt>
 <dd>Returns the value associated to the <code><var>key</var></code>, or <code>undefined</code> if there is none.</dd>
 <dt>{{jsxref("Map.has", "Map.prototype.has(<var>key</var>)")}}</dt>
 <dd>Returns a boolean asserting whether a value has been associated to the <code><var>key</var></code> in the <code>Map</code> object or not.</dd>
 <dt>{{jsxref("Map.prototype.keys()")}}</dt>
 <dd>Returns a new <code>Iterator</code> object that contains the <strong>keys</strong> for each element in the <code>Map</code> object in insertion order.</dd>
 <dt>{{jsxref("Map.set", "Map.prototype.set(<var>key</var>, <var>value</var>)")}}</dt>
 <dd>Sets the <code><var>value</var></code> for the <code><var>key</var></code> in the <code>Map</code> object. Returns the <code>Map</code> object.</dd>
 <dt>{{jsxref("Map.prototype.values()")}}</dt>
 <dd>Returns a new <code>Iterator</code> object that contains the <strong>values</strong> for each element in the <code>Map</code> object in insertion order.</dd>
 <dt>{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}</dt>
 <dd>Returns a new <code>Iterator</code> object that contains <strong>an array of <code>[<var>key</var>, <var>value</var>]</code></strong> for each element in the <code>Map</code> object in insertion order.</dd>
</dl>

<h2 id="Examples">Examples</h2>

<h3 id="Using_the_Map_object">Using the <code>Map</code> object</h3>

<pre class="brush: js notranslate">let myMap = new Map()

let keyString = 'a string'
let keyObj    = {}
let keyFunc   = function() {}

// setting the values
myMap.set(keyString, "value associated with 'a string'")
myMap.set(keyObj, 'value associated with keyObj')
myMap.set(keyFunc, 'value associated with keyFunc')

myMap.size              // 3

// getting the values
myMap.get(keyString)    // "value associated with 'a string'"
myMap.get(keyObj)       // "value associated with keyObj"
myMap.get(keyFunc)      // "value associated with keyFunc"

myMap.get('a string')    // "value associated with 'a string'"
                         // because keyString === 'a string'
myMap.get({})            // undefined, because keyObj !== {}
myMap.get(function() {}) // undefined, because keyFunc !== function () {}
</pre>

<h3 id="Using_NaN_as_Map_keys">Using <code>NaN</code> as <code>Map</code> keys</h3>

<p>{{jsxref("NaN")}} can also be used as a key. Even though every <code>NaN</code> is not equal to itself (<code>NaN !== NaN</code> is true), the following example works because <code>NaN</code>s are indistinguishable from each other:</p>

<pre class="brush: js notranslate">let myMap = new Map()
myMap.set(NaN, 'not a number')

myMap.get(NaN)
// "not a number"

let otherNaN = Number('foo')
myMap.get(otherNaN)
// "not a number"
</pre>

<h3 id="Iterating_Map_with_for..of">Iterating <code>Map</code> with <code>for..of</code></h3>

<p>Maps can be iterated using a <code>for..of</code> loop:</p>

<pre class="brush: js notranslate">let myMap = new Map()
myMap.set(0, 'zero')
myMap.set(1, 'one')

for (let [key, value] of myMap) {
  console.log(key + ' = ' + value)
}
// 0 = zero
// 1 = one

for (let key of myMap.keys()) {
  console.log(key)
}
// 0
// 1

for (let value of myMap.values()) {
  console.log(value)
}
// zero
// one

for (let [key, value] of myMap.entries()) {
  console.log(key + ' = ' + value)
}
// 0 = zero
// 1 = one
</pre>

<h3 id="Iterating_Map_with_forEach">Iterating <code>Map</code> with <code>forEach()</code></h3>

<p>Maps can be iterated using the {{jsxref("Map.prototype.forEach", "forEach()")}} method:</p>

<pre class="brush: js notranslate">myMap.forEach(function(value, key) {
  console.log(key + ' = ' + value)
})
// 0 = zero
// 1 = one
</pre>

<h3 id="Relation_with_Array_objects">Relation with Array objects</h3>

<pre class="brush: js notranslate">let kvArray = [['key1', 'value1'], ['key2', 'value2']]

// Use the regular Map constructor to transform a 2D key-value Array into a map
let myMap = new Map(kvArray)

myMap.get('key1') // returns "value1"

// Use Array.from() to transform a map into a 2D key-value Array
console.log(Array.from(myMap)) // Will show you exactly the same Array as kvArray

// A succinct way to do the same, using the spread syntax
console.log([...myMap])

// Or use the keys() or values() iterators, and convert them to an array
console.log(Array.from(myMap.keys())) // ["key1", "key2"]
</pre>

<h3 id="Cloning_and_merging_Maps">Cloning and merging <code>Map</code>s</h3>

<p>Just like <code>Array</code>s, <code>Map</code>s can be cloned:</p>

<pre class="brush: js notranslate">let original = new Map([
  [1, 'one']
])

let clone = new Map(original)

console.log(clone.get(1))       // one
console.log(original === clone) // false (useful for shallow comparison)</pre>

<div class="blockIndicator note">
<p><strong>Important:</strong> Keep in mind that <em>the data itself</em> is not cloned.</p>
</div>

<p>Maps can be merged, maintaining key uniqueness:</p>

<pre class="brush: js notranslate">let first = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
])

let second = new Map([
  [1, 'uno'],
  [2, 'dos']
])

// Merge two maps. The last repeated key wins.
// Spread operator essentially converts a Map to an Array
let merged = new Map([...first, ...second])

console.log(merged.get(1)) // uno
console.log(merged.get(2)) // dos
console.log(merged.get(3)) // three</pre>

<p>Maps can be merged with Arrays, too:</p>

<pre class="brush: js notranslate">let first = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
])

let second = new Map([
  [1, 'uno'],
  [2, 'dos']
])

// Merge maps with an array. The last repeated key wins.
let merged = new Map([...first, ...second, [1, 'eins']])

console.log(merged.get(1)) // eins
console.log(merged.get(2)) // dos
console.log(merged.get(3)) // three</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>



<p>{{Compat("javascript.builtins.Map")}}</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("Set")}}</li>
 <li>{{jsxref("WeakMap")}}</li>
 <li>{{jsxref("WeakSet")}}</li>
</ul>