Antonio B R
Antonio B R

Reputation: 393

How to properly check if a Set is empty

I've come with a question regarding the best way to check if a Javascript Set is empty. According with documentation, there is no a straightforward method to check or get Set items.

I think it happens same with Map.

I've come up with some ideas (Node.js), but I'm not quite sure what's better.

const assert = require('assert');

const emptySet = new Set()
assert.strictEqual(![...emptySet].length, true)
assert.strictEqual(emptySet.values().next().value === undefined, true)
assert.strictEqual(emptySet.entries().next().value === undefined, true)

const twoItemsSet = new Set([ 'foo', 'bar' ])
assert.strictEqual(![...twoItemsSet].length, false)
assert.strictEqual(twoItemsSet.values().next().value === undefined, false)
assert.strictEqual(twoItemsSet.entries().next().value === undefined, false)

Upvotes: 27

Views: 35040

Answers (1)

Kyle Becker
Kyle Becker

Reputation: 1440

emptySet.size == 0

MDN Documentation

Upvotes: 58

Related Questions