Introduction
Checking if a key exists in a JavaScript object is important when working with data. It helps developers avoid errors and handle objects properly. There are different ways to check for a key, such as using the in operator, the hasOwnProperty() method, or the Object.hasOwn() method. Each method works in a different way. Some check only the object’s own properties, while others also check inherited properties. Knowing which method to use can make your code more accurate and efficient.

In this article, you will learn simple ways to check if a key exists in a JavaScript object and when to use each method.
1. Using in Operator
The in operator is a simple way to check if a key exists in an object. It returns true if the key is present in the object, even if the value associated with it is undefined.
Syntax
"key" in object
Example
const student = {
name: "John",
age: 21,
course: "Computer Science"
};
console.log("name" in student);
console.log("grade" in student);
Output
true
false
Explanation:
- The first check returns true because the key name exists in the student object.
- The second check returns false since grade is not a key in the object.