WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Check If a Key Exists in a JavaScript Object

Topic: JavaScript / jQueryPrev|Next

Answer: Use the in Operator

You can simply use the in operator to check if a particular key or property exists in a JavaScript object. This operator returns true if the specified key exists in the object, otherwise returns false.

Let's take a look at the following example to understand how it basically works:

// Sample object
var myCar = {
    make: "Ford",
    model: "Mustang",
    year: 2021
};

// Test if a key exists in the object
if("model" in myCar === true) {
    alert("The specified key exists in the object.");
} else {
    alert("The specified key doesn't exist in the object.");
}

If you set the property of an object to undefined but do not delete it, the in operator will return true for that property. Let's check out an example to understand this better:

// Sample object
var myCar = {
    make: "Ford",
    model: "Mustang",
    year: 2021
};

// Setting a property to undefined
myCar.model = undefined;

// Deleting a property
delete myCar.year;

// Test if properties exist
console.log("make" in myCar);  // Prints: true
console.log("model" in myCar); // Prints: true
console.log("year" in myCar);  // Prints: false

See the tutorial on JavaScript Objects to learn more about creating and manipulating objects.


Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties