It seems to me that there are four different ways I can determine whether a given object (e.g. foo
) has a given property (e.g. bar
) defined:
To add to what others have said, if you just want to know if a property exists and has a non-falsey value (not undefined
, null
, false
, 0
, ""
, NaN
, etc...), you can just do this:
if (foo.bar) {
// code here
}
As long as falsey values are not interesting to you for your particular circumstance, this shortcut will tell you if the variable has been set to something useful for you or not.
If you want to know if the property exists on the object in any way, I find this the most useful, brief and readable:
if ('bar' in foo) {
// code here
}
One can also use something similar on function arguments (again as long as a falsey value isn't something you care about):
function foo(bar) {
if (bar) {
// bar was passed and has some non-falsey value
}
}