Check if it exists

Perhaps you have a situation where you declare a person object that may or may not get a "birthday" property declared, but we want processing to continue regardless. Outputting the properties and their values is great for us Humans, but the code cannot "see" missing items. However in code we can instead just check if the property exists.

Keep in mind that JavaScript considers anything that is not zero, null, or undefined to be equivalent to a positive value. So, we can write code like this:

if (myObject.birthdate) {
alert(myObject.birthdate);
}

If the birthdate property is not defined, then our IF condition will be "undefined" or false and the alert will never be executed.

There is one minor problem here though - if the myObject variable has not been defined, you'll still get an error here. The code would need to be changed to check for the object AND the property.

if ( myObject && myObject.birthdate ) {
alert(myObject.birthdate);
}

When troubleshooting, this type of code requirement is likely to come up on a regular basis. This can apply to any object or property, or even a simple variable or function.