I did a series of tests for different array values:
Tests:
x === 0
x === ''
x === false
x === undefined
x === NaN
x === null
x === []
x === {}
x == 0
x == ''
x == false
x == undefined
x == NaN
x == null
x == []
x == {}
Result:
if x is either:
[NaN]
[false]
it fails all tests.
if x is either:
[null]
[]
[[]]
[[[yep, no matter how deep]]]
[undefined]
['']
it passes:
x==0
x==''
x==false
if x is either:
[0]
[{}]
it passes
x==0
x==false
Am I missing something? Is there something an empty array []
strictly equal to (===
)?
Also, for these values: [NaN],[false], [null], [], [[]], [undefined], [''], [0], [{}]
, only [].length
is equal to 0
What are the best practices on how to check if an array is empty []
? If there are competing best practices, in which situations is it best to use them?
An empty array is strictly equal only to itself. More properly, an expression that evaluates to a reference to some particular empty array is only strictly equal to another reference to that same array.
That holds for any sort of object, not just arrays, and not just empty arrays. There's no built-in way to provide your own special behavior for equality comparisons with ===
.
Comparisons with ==
are another story because of the type conversions that are implicitly performed. It's still true, however, than object comparisons even with ==
(that is, when no type conversions are performed) follow the same rule: a reference to an object is only equal to another reference to the same object.
Note also that
[] === []
is false
because those are two different empty arrays. Similarly,
[1, 2] === [1, 2]
is false
, as is
{a: "hello"} === {a: "hello"}
Every array or object initializer expression creates a unique object, so even though they look the same, they're not equal under the rules of JavaScript ===
comparison.
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