Skip to content

Commit bcfd48e

Browse files
authored
Update Map usage explanation in article.md
Clarify the correct usage of Map methods and explain the implications of using map[key].
1 parent 51bc6d3 commit bcfd48e

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

1-js/05-data-types/07-map-set/article.md

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,25 @@ alert( map.size ); // 3
4141

4242
As we can see, unlike objects, keys are not converted to strings. Any type of key is possible.
4343

44-
```smart header="`map[key]` isn't the right way to use a `Map`"
45-
Although `map[key]` also works, e.g. we can set `map[key] = 2`, this is treating `map` as a plain JavaScript object, so it implies all corresponding limitations (only string/symbol keys and so on).
44+
````smart header="`map[key]` isnt the correct way to use a `Map`"
45+
Although you can technically write `map[key] = value`, this does **not** store the data inside the `Map` collection.
4646

47-
So we should use `map` methods: `set`, `get` and so on.
47+
Instead, it simply adds a regular property to the `Map` object itself—just like with plain JavaScript objects—and the key is always converted to a string.
48+
49+
For example:
50+
51+
```js run
52+
let map = new Map();
53+
map["1"] = "test"; // adds a property, not a Map entry
54+
55+
console.log(map.get("1")); // undefined
56+
console.log(map["1"]); // "test"
4857
```
4958

59+
To properly store and retrieve data in a `Map`, always use its methods:
60+
`map.set(key, value)` and `map.get(key)`.
61+
````
62+
5063
**Map can also use objects as keys.**
5164
5265
For instance:

0 commit comments

Comments
 (0)