How do I check if a particular key exists in a JavaScript object or array?
If a key doesn\'t exist, and I try to access it, will it return false? Or throw an error?<
Answer:
if ("key" in myObj)
{
console.log("key exists!");
}
else
{
console.log("key doesn't exist!");
}
Explanation:
The in
operator will check if the key exists in the object. If you checked if the value was undefined: if (myObj["key"] === 'undefined')
, you could run into problems because a key could possibly exist in your object with the undefined
value.
For that reason, it is much better practice to first use the in
operator and then compare the value that is inside the key once you already know it exists.