Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property detection: Using 'in' versus trying to access property

Tags:

javascript

Have to mention: I know a bit JavaScript but I'm not very deep into it.

Always considered this the correct way to check if a property is available on an object:

if (window.console) {
  // doSomething
}

Yesterday I've seen code in which this technique was used:

if ('console' in window) {
  // doSomething
}

Are both techniques equivalent? Or do they distinguish?

like image 401
bo256 Avatar asked Jan 05 '16 07:01

bo256


1 Answers

Nope. They have a difference.

First one checks if the value of window.console is Truthy and the second one checks of the console property exists in window.

Let's say you create a variable like this.

window.myName = "";

Now, if (window.MyName) will fail to satisfy the condition, as empty strings are Falsy in JavaScript.

console.log(Boolean(window.myName)); // false

But if ("myName" in window) will satisfy the condition, as myName is a property of window object.

console.log(Boolean("myName" in window)); // true

Note: in operator will return true even if the property being tested is somewhere in the prototype hierarchy. For example,

console.log("toString" in {});  // true

It returns true because the object {} inherits the method toString.

If you want to make sure that the property exists on the object itself, then you should use Object.prototype.hasOwnProperty, like this

console.log({}.hasOwnProperty("toString")); // false
like image 196
thefourtheye Avatar answered Nov 13 '22 20:11

thefourtheye