Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
Check if a property exists on an object when the object may not exists either?

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;
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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');
about 4 years ago · Juan Pablo Isaza Report

0

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})

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!