bo256 bo256 - 4 years ago 111
Javascript Question

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

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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download