A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

How to Check If a Key Exists in a JavaScript Object
Q:

How to Check If a Key Exists in a JavaScript Object

0

How to Check If a Key Exists in a JavaScript Object

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now