I’m creating a set from two arrays, and I’m encountering a confusing TypeError:
const a_list = [1, 2, 3];
const b_list = [3, 4, 5];
const combined = new Set()
.union(a_list) // <<<< Error is thrown here.
.union(b_list);
This fails with the error:
Uncaught TypeError: The .size property is NaN
at Set.union (<anonymous>)
at <anonymous>:2:6
How can the set’s .size
property be NaN? When I test it in the console, the default size is 0:
> new Set().size
< 0
2
Answers
Set.prototype.union()
operates on values ofSet
, not arrays. The problem you’re seeing stems from the fact that[].size
isundefined
andNumber(undefined)
returnsNaN
. When you wrap both of your inputs in aSet
, the issue is resolved.Sets have a
size
property, but arrays do not. And these are arrays:The
union
function onSet
expects "a set-like object", and arrays are not that.You can convert them to sets: