DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How to check if an ES6 Map or Set is empty?
Calvin Torra
Calvin Torra

Posted on • Originally published at calvintorra.com

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
Enter fullscreen mode Exit fullscreen mode

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 } }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Preeeety useful.

Top comments (0)

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.