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)
Set. isEmpty() method is used to check if a Set is empty or not. It returns True if the Set is empty otherwise it returns False.
In python, an empty set always evaluates to false. So when we passed an empty set to the if condition it'll be evaluated to false. But the not operator reverses the false value to true value.
emptySet.size == 0
MDN Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With