Reputation: 5844
I have an object called foo
. I want to check if it has the property bar
.
Should I use this:
if (typeof foo.bar !== "undefined")
Or this:
if ("bar" in foo)
Is there any difference?
Upvotes: 3
Views: 268
Reputation: 4991
Your question is like "which one is the 'best' for checking the presence of a property in an object", therefore the latter ("bar" in foo
) is what you're looking for.
The result of if("bar" in foo)
is "only do this if there's a 'bar' property in foo" which what you're asking for.
You could also go for typeof foo.bar != "undefined"
but it would be useless overkill.
Upvotes: 0
Reputation: 1931
"typeof" does not care if the property exists or not and it will return undefined even if the property exists but has a value of "undefined"
While, "in" will return true if the property exists and has a value of "undefined"
For an example, the following would return either true or false depending on which you use:
let person = {
name: 'John',
age: undefined
}
console.log('age' in person)
// true
console.log(typeof person.age !=="undefined")
//false
Upvotes: 4