Checking if a key exists in a JavaScript object?

Created by Ates GoralLinked to 24.2m issues across 269 teams

tl;dr

Yes, you can check if a key exists in a JavaScript object using the hasOwnProperty() method.

For example, if we have an object person with the properties name, age, and gender, we can check if the name property exists using the following code:

if (person.hasOwnProperty('name')) { console.log('The person object has a name property'); }

In this example, the hasOwnProperty() method is used to check if the name property exists in the person object. If it does, the console.log() statement will be executed.