I can check if a property exists like so:
let myObject = {};
let exists = myObject.myProperty !== undefined;
But how can I check if the property exists when myObject is not defined either, the following errors:
// let myObject = {}; // do not set this
let exists = myObject.myProperty !== undefined;
There are several things at play here.
First, to check if the object exists in the current scope, you should use the typeof operator:
let objectExists = typeof myObject !== 'undefined'
this way, the interpreter won't throw an error.
Second, to check if the object has a specific property, it's still best to use the old in operator
let propertyExists = 'myProperty' in myObject
Both of these expressions return a boolean value, true or false.
So, for safe checking, you might use:
if(typeof myObject !== 'undefined' && myProperty in myObject) {
// do your stuff
}
if you try to use the newer form of myObject?.myProperty it will still throw a ReferenceError if you haven't declared myObject
and if you use myObject.hasOwnProperty(myProperty) you might get a misleading result, if your object inherits from another and the property belongs to the ancestor
if myObject doesn't exist at all, use try/catch
let exists;
try {
exists = myObject.hasOwnProperty('myProperty');
}catch(err){
console.log(err.message)
}
if it's null or undefined, Use ?. (optional chaining) operator:
let exists = myObject?.hasOwnProperty('myProperty');
Since the myObject variable might not be defined (as per your question), you must wrap your code with try/catch in order for the flow not to break:
let exists = false;
try{
// try to access "a" property of myObject
exists = myObject?.a;
}
catch{
// because myObject is not defined, the catch block is invoked
console.log("myObject", "is not defined")
}
console.log({exists})