Reputation: 153
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?
Upvotes: 5
Views: 81
Reputation: 2604
No. They have a difference.
When using the in
operator, you check if the property is specified in the given object and not it's value. For example:
var obj = { foo: undefined }
obj.foo !== undefined; // false
'foo' in obj; // true
Hope It Helps
Upvotes: 4
Reputation: 239493
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
Upvotes: 5
Reputation: 15292
When you say window.console
it will check for the property console
in window
object.I does not consider weather console
property is own property of window object or it is inherited from parent.
On the other side in console in window
, the in will make sure property is exist as own property of window object and not inherited from parent.
Upvotes: 1
Reputation: 57
In your case it's equivalent. When you use in operator, it looks that property exisits in object. And when you use if (window.console) it looks that window.console is a truth value.
Upvotes: 1