0

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?

Stephen Jenkins
  • 1,776
  • 3
  • 24
  • 39

1 Answers1

5

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497