"typeof" opposite "in" to check if a property exists in an object

I have an object named foo

. I want to check if it has a property bar

.

Should I use this:

if (typeof foo.bar !== "undefined")

      

Or that:

if ("bar" in foo)

      

Is there a difference?

+3


source to share


2 answers


"typeof" doesn't matter if the property exists or not and it will return undefined even if the property exists, but it is "undefined"

While "in" will return true if the property exists and is "undefined"



As an example, the following returns either true or false depending on what you are using:

let person = {
  name: 'John',
  age: undefined
}

console.log('age' in person)
// true
console.log(typeof person.age !=="undefined") 
//false

      

+3


source


Your question is like "the one that is the" best "for checking if a property exists in an object, so the last ( "bar" in foo

) is what you are looking for.

The result if("bar" in foo)

is "only this if foo has the" bar "property you are asking for.



You can also go for it typeof foo.bar != "undefined"

, but that would be a useless overkill.

0


source







All Articles