Currently, I am delving into the world of arrays in JavaScript. My main inquiry revolves around determining the equivalence of the two tests below:
var test = 2;
console.log(test in [1,2,3]);
console.log([1,2,3].indexOf(test) != -1);
Initially, these tests appear to yield similar results. However, after coming across responses on platforms like this and insights from the book I am currently engrossed in, doubts have arisen. It is argued that using the in
operator with an array is not supported, but rather intended for objects. This discrepancy prompts the question: why do individuals opt for .indexOf(x)
, presumed to be linear time, over in
, assumed to offer constant time efficiency?