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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With