Juris Juris - 3 months ago 26
Javascript Question

Is array with one element equal to the element?

I am doing some comparisons in JavaScript. I copied over some code like this:

if (input.val() != input.data('original') )
//do stuff

I was expecting I will have to change something, because at this instance
<select multiple>
with number of selectable options limited to 1. But it worked without changes.

I checked and it turns out that:

13 == [13] //true
13 === [13] //false

It was unexpected that the comparison unwraps array.

Is this an intended and documented feature in JavaScript that I can use and rely on? Or does this only work for me because some browser developer decided to make it work?


When loose equality ( == ) is used to compare Object and Number:

it attempts to convert its object argument to a primitive value, by attempting > to invoke varying sequences of A.toString and A.valueOf methods on A

So what you actually get by doing that:

13 == [13]


13 == ([13].toString().valueOf())