Reputation: 11
It happens to me lots of times in javascript, php and other languages.
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
Reputation: 3479
Yes, you can use optional chaining operator for that
if (myObject?.myProp === "myTestValue") {
// execute code
}
Upvotes: 3