Câu hỏi phỏng vấn Javascript
Câu hỏi

What's the difference between...

Câu trả lời

The difference between ES6 Map and WeakMap primarily revolves around key types, garbage collection, iteration capabilities, and the presence of certain properties like size. Here's a detailed breakdown of these differences:

Key Types

  • Map: Can use any value as a key, including primitives like strings and numbers, as well as objects and functions[1][2][5].
  • WeakMap: Only accepts objects as keys. Using non-object keys (like strings or numbers) will result in an error[1][2][5].

Garbage Collection

  • Map: Maintains strong references to its keys and values. This means that as long as the Map exists, the keys and values it contains are preserved in memory, preventing them from being garbage collected[1][2][5][7].
  • WeakMap: Holds keys weakly, meaning if there are no other references to a key (an object) outside of the WeakMap, that key can be garbage collected. This feature makes WeakMap suitable for managing memory in applications where objects are dynamically added and removed[1][2][5][7].

Iteration Capabilities

  • Map: Supports iteration over its elements, allowing access to keys, values, and entries directly. It provides methods like keys(), values(), and entries() for this purpose[1][2][5].
  • WeakMap: Does not support iteration. Methods like keys(), values(), and entries() are not available in WeakMap because its elements are not enumerable. This is due to the non-deterministic nature of garbage collection which can remove keys at any time[1][2][5].

Size Property

  • Map: Has a size property that retu...
expert

expert

Gợi ý câu hỏi phỏng vấn

senior

What is the new keyword in JavaScript?

middle

What's a typical use case for anonymous functions?

junior

Why would you use something like the load event? Does this event have disadvantages? Do you know
any alternatives, and why would you use those?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào