Property detection: using 'in' against attempting to access a property

Must mention: I know a bit of JavaScript, but I'm not very deep into it.

Always consider this the right way to check if a property is available to an object:

if (window.console) { // doSomething } 

Yesterday, I saw code that used this method:

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

Are both methods equivalent? Or do they distinguish?

+5
source share
4 answers

Nope. They have a difference.

First, it checks to see if the value of window.console Truthy, and the second checks the console property in window .

Suppose you created such a variable.

 window.myName = ""; 

Now if (window.MyName) will not be able to fulfill the condition, since empty lines are false in JavaScript.

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

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

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

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

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

Returns true because the {} object inherits the toString method.

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

 console.log({}.hasOwnProperty("toString")); // false 
+4
source

No. They have a difference.

When using the in operator, you check to see if a property is specified in a given object, not a value. For instance:

 var obj = { foo: undefined } obj.foo !== undefined; // false 'foo' in obj; // true 

Hope this helps

+4
source

In your case, this is equivalent. When you use in an operator, it looks like the exisits property in the object. And when you use if (window.console), it looks like window.console is the value of truth.

+1
source

When you say window.console , it will check the console property in the window object. I don’t think that the weather console property is a native property of the window object or it is inherited from the parent.

On the other hand, in console in window , make sure that the property exists as a native property of the window object and is not inherited from the parent.

+1
source

Source: https://habr.com/ru/post/1239864/


All Articles