Bubble Foundry


A Subtle Javascript Mistake

by Peter.

I was just pounding my head against what turned out to be a simple Javascript misconception that I hope I can save people from: in tests for the existance of a key, not a value, in an object or array. So the following work:

  var myObj = {1: "one", 2: "two"}
  1 in myObj // -> true
  2 in myObj // -> true
  var myArr = [1, 2]
  0 in myArr // -> true
  1 in myArr // -> true

But you might be surprised at the following results (I was):

  2 in myArr // -> false

That is because myArr has values 1 and 2 at keys 0 and 1, respectively. To test the existence of a value in an array, you need to use indexOf. For instance:

  myArr.indexOf(1) // -> 0
  myArr.indexOf(2) // -> 1
  myArr.indexOf("doesn't exist") // -> -1

As you can see, -1 indicates the value does not exist in the array.