How to find the size of map in javascript

You are treating Map like an array and using [] to access key/value items of it. You need to use the actual methods of Map. Instead of [], use .get() and .set().

Right now, you are setting the actual properties of the Map which are not the same as the actual tracked iterable k/v items stored by the data structure.

// Incorrect
const m1 = new Map();

m1["foo"] = "bar";

console.log(m1.length); // undefined
console.log(m1.size); // 0

// Correct
const m2 = new Map();

m2.set("foo", "bar");

console.log(m2.length); // undefined
console.log(m2.size); // 1

Refer How to check if a Map or Set is empty?.

It works with empty map as well as map with values.

var list = {}; console.log(Object.keys(list).length );

result = 0

list = {"key":"hello"}; console.log(Object.keys(list).length );


Map type has a special prototype to get length of the Map object

const map1 = new Map();

map1.set('a', 'alpha');
map1.set('b', 'beta');
map1.set('g', 'gamma');

console.log(map1.size);
// expected output: 3

Referance from developer.mozilla.org

Tags:

Javascript