9

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?

1
  • 4
    What are the best practices on how to check if an array is empty, how about array.length==0? Commented Jul 24, 2016 at 3:09

1 Answer 1

29

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the clear and concise answer. I'll go with emptyArray.length == 0 to check for array emptiness then.
Just throwing it out there- since "0" is falsy in JavaScript you can also just check if (!emptyArray.length)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.