0

Here

var a = {}

When

if(typeof a.b == "undefined"){
  console.log("undefined");
}

if (!a.b){
  console.log("undefined");
}

both return "undefined" and when

if(typeof c.b == "undefined"){
  console.log("undefined");
}

if (!c.b){
  console.log("undefined");
}

both raise error c is not defined

It looks like 2 if-else statements above are working the same. So which way is better?

yeuem1vannam
  • 957
  • 1
  • 7
  • 15

3 Answers3

2

If you are looking for a way to check member existence, you should use in operator

if ("b" in a) {
    ...
}

The error c is not defined raised, because c is not defined anywhere in the program.

What typeof a.b will return, is the type of data which is stored in a.b. What if b actually exists and it actually holds the value undefined? Both typeof a.b and !a.b will evaluate to a truthy value. So, they should not be used for member existence checks.

Please check this answer to know why in should be preferred for member existence.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

I would use the in operator

if ('b' in a) {
    ...
}

I'd use it because it was done exactly for checking if a property exists in an object, and because it's much more readable than the others (IMO).

However, it doesn't matter which one is faster because you'd be microoptimizing (unless you that operation millions or billions of times).

Cheers

PS: c is not defined happens because with c.b you tried to acces the b member of an undefined variable (c)

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
0

I'm not sure what you're trying to achieve but there are two problems. The first part is checking for a property being defined in an object. The first if is checking if the type of the property is defined or not but it could be "undefined" on purpose.

Use to check if the object has the property.

if(b.hasOwnProperty("c")) {

}

If you want to "lookup" for the property in the whole prototype chain then use in:

if ("c" in b) {

}

Otherwise checking of b.c is "undefined" means that the value returned by "b.c" is of type "undefined". It doesn't mean that b has or doesn't have the property "c".

The second block is failing because "c" isn't defined in the global scope. You cannot access a property of an undefined object which will cause an error.

note

If you don't have prototype chains, hasOwnProperty should be faster in most cases.

Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99