DEV Community

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

Posted on • Edited on • Originally published at calvintorra.com

4 1

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

Join my newsletter Here:

Once a week, I share my best finds on:

  • AWS
  • JavaScript
  • Web Scraping
  • Indie Hacking

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 doesnt 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.

Join my newsletter Here:

Once a week, I share my best finds on:

  • AWS
  • JavaScript
  • Web Scraping
  • Indie Hacking

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay