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

### Learn These 6 Figure Scraping Techniques As A Side Hustle

Access secret data points from SaaS websites and much more.

→ 6 Figure Scraping Guide ←

Use this data for your own startup or sell it to those that need it.

## No spam, just Javascript, web3 and indie hacking!

We won’t send you spam. Unsubscribe at any time.

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()
// 2