How to check if an ES6 Map or Set is empty?

How to check if an ES6 Map or Set is empty?

While working with normal objects in Javascript we’re able to check if the object is empty. The same with a typical array.

We can use Object.keys() which returns an array and then we can check the length of that array.

const userObject = { name: 'Calvin', age: 200};

console.log(Object.keys(userObject));
// [ 'name', 'age' ]

console.log(Object.keys(userObject).length === 0);
// false
It doesn’t seem too common to do the same thing with arrays but Object.keys() still works.

const userArray = ['Calvin', 200, 1000]

console.log(Object.keys(userArray));
// [ '0', '1', '2' ]

console.log(Object.keys(userArray).length === 0);
// false

When working with Maps and Sets, we’re not able to check the data using Object.keys(). We’ll continuously get back an empty array with a length of 0 🙁

const userMap = new Map()
userMap.set('Calvin', {age:200, height:1000})

console.log(Object.keys(userMap))
// []
console.log(Object.keys(userMap).length === 0)
// true
console.log(userMap)
// Map { 'Calvin' => { age: 200, height: 1000 } }

This is where we can use size property. Both Maps and Sets come with the size property and it returns the length of these two ES6 data types.

const userMap = new Map()
userMap.set('Calvin', {age:200, height:1000})

console.log(userMap.size)
// 1

const userSet = new Set()
userSet.add('Calvin')
userSet.add(200)

console.log(userSet)
// Set { 'Calvin', 200 }

console.log(userSet.size)
// 2

Preeeety useful.