Aidenhjj Aidenhjj - 1 year ago 59
Javascript Question

What is the difference between `var in array` and `array.indexOf(var)`?

I am trying to get my head around arrays in JS. My question is; are the following two tests equivalent?

var test = 2;
console.log(test in [1,2,3]);
console.log([1,2,3].indexOf(test) != -1);

They seem to be, but then answers like this and the book I am reading suggest that you can't do
on an array, only on an object. Looking for clarity. There must be a reason that people use
(which I assume is linear time) and not
(which I assume is constant time).

Answer Source

No. They are completely different.

test in [1,2,3] checks if there is a property named 2 in the object. There is, it has the value 3.

[1,2,3].indexOf(test) gets the first property with the value 2 (which is in the property named 1)

suggest that you can't do in on an array, only on an object

Arrays are objects. (A subclass if we want to use classical OO terminally, which doesn't really fit for a prototypal language like JS, but it gets the point across).

The array [1, 2, 3] is like an object { "0": 1, "1": 2, "2": 3 } (but inherits a bunch of other properties from the Array constructor).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download