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
Set.prototype.union()
operates on values of Set
, not arrays. The problem you're seeing stems from the fact that [].size
is undefined
and Number(undefined)
returns NaN
. When you wrap both of your inputs in a Set
, the issue is resolved.
const a_list = new Set([1, 2, 3]);
const b_list = new Set([3, 4, 5]);
const combined = new Set()
.union(a_list)
.union(b_list);