Map.prototype.set and get
map.set(key, value)
map.get(key)
map.has(key)Store and retrieve a value by key using SameValueZero equality.
Returns: set() returns the map. get() returns the value, or undefined when the key is missing. has() returns a boolean.
- undefined is a valid stored value, so has() is the reliable missing-key test.
- Map iteration order is insertion order, including for numeric keys. That differs from Object.keys().
const map = new Map();
map.set(NaN, "nan");
console.log(map.get(NaN), map.has(NaN), map.size);
map.set(0, "zero");
map.set(-0, "neg");
console.log(map.get(0), map.get(-0), map.size);
const key = { x: 1 };
const byObject = new Map([[key, "a"]]);
console.log(byObject.get(key), byObject.get({ x: 1 }));Expected output
nan true 1
neg neg 2
a undefinedRelated: Object keys