2

Is the IN operator a linear search operation, like the indexOf() array method?

I want to check the presence of a property in an object for each element in an array, using if (key in obj), in order to avoid nesting iterative operations.

I've checked the spec and there is very little information about the IN operator.

Does it iterate over an object's keys, resulting in a linear time operation? Or does it simply attempt a direct lookup of the key, resulting in a constant time operation?

  • That would depend on the implementation, but if you need the operation, then you need it. Have you found an actual performance problem related to the `in` operator? Because if there is an issue, `in` wouldn't be the first place I'd look. –  Apr 27 '17 at 19:48
  • No actual performance problem, I'm just trying to make a solution to a practice problem maximally efficient, and I realized that I have no idea how IN works underneath the hood. – Neil Murphy Apr 27 '17 at 19:50
  • 1
    Property access should be `O(1)`, not a linear search. – Bergi Apr 27 '17 at 19:55
  • 1
    There is no reason why the time complexity for `key in obj` would not be the same as for `obj[key]`. – trincot Apr 27 '17 at 20:03

0 Answers0