user2693460
user2693460

Reputation: 11

How to know if an object property exists and has a value

It happens to me lots of times in javascript, php and other languages.

  1. I need to know if an object exists
  2. I need to know if that object has a property
  3. I need to check if the value of that property meets a condition

I use to do like this :

if (typeof myObject != "undefined") {
  if (myObject.hasOwnProperty('myProp') {
    if (myObject.myProp == "myTestValue") {
      // execute code
    }
  }
}

if I do just like this :

if (myObject.myProp == "myTestValue") {
  // execute code
}

it raises an error if object or property doesn't exist.

Is there a way of doing that with one line of code ?

Tks

Upvotes: 1

Views: 5561

Answers (1)

n1md7
n1md7

Reputation: 3479

Yes, you can use optional chaining operator for that

if (myObject?.myProp === "myTestValue") {
  // execute code
}

Upvotes: 3

Related Questions