Skip to main content
Good point about falsy values, but bad suggestion to use `typeof`.
Source Link
Sebastian Simon
  • 19.8k
  • 8
  • 61
  • 87
if (typeof x.key != "undefined") {

}
if(x.hasOwnProperty("key")){
  // …
}

Becausebecause

if (x.key)
if(x.key){
  // …
}

fails if x.key resolves to falseis falsy (for example, x.key ==== "").

if (typeof x.key != "undefined") {

}

Because

if (x.key)

fails if x.key resolves to false (for example, x.key = "").

if(x.hasOwnProperty("key")){
  // …
}

because

if(x.key){
  // …
}

fails if x.key is falsy (for example, x.key === "").

Crucial formatting, etc.
Source Link
Peter Mortensen
  • 31.5k
  • 22
  • 110
  • 134
if (typeof x.key != "undefined") {

}

Because

if (x.key)

fails if if x.key resolves to false (egfor example, x.key = "").

if (typeof x.key != "undefined"){

}

Because

if (x.key)

fails if x.key resolves to false (eg x.key = "").

if (typeof x.key != "undefined") {

}

Because

if (x.key)

fails if x.key resolves to false (for example, x.key = "").

added 28 characters in body
Source Link
kapa
  • 78.9k
  • 21
  • 166
  • 178

if (typeof x.key != "undefined"){

if (typeof x.key != "undefined"){

}

} Because

if (x.key)

Because iffails (x.key) fails if x.keyif x.key resolves to falsefalse (eg x.key = ""x.key = "").

if (typeof x.key != "undefined"){

}

Because if (x.key) fails if x.key resolves to false (eg x.key = "").

if (typeof x.key != "undefined"){

}

Because

if (x.key)

fails if x.key resolves to false (eg x.key = "").

Source Link
werehamster
werehamster
Loading