Stephen Jenkins
Stephen Jenkins

Reputation: 1836

What benefit does using `in` have over object.prop?

We all see the feature detects doing something like:

var touch = function () {
  return 'ontouchstart' in window;
};

But I'm wondering if there are any other benefits to using the in operator over something like this (which saves a few bytes)?

var touch = function () {
  return !!window.ontouchstart;
};

Are there any other benefits to using in?

Upvotes: 0

Views: 85

Answers (1)

thefourtheye
thefourtheye

Reputation: 239473

They both are entirely different.

When you do

!!window.ontouchstart

you are checking if the value of window.ontouchstart is truthy, but

'ontouchstart' in window

checks if ontouchstart exists in window object.

Another problem with using !!window.ontouchstart to check member existence is that, even if ontouchstart exists and if it has a falsy value, for example undefined, null, false or 0, it will still return false. So, it should NOT be used to check the member existence.

Upvotes: 5

Related Questions