-1

Is there an easier way to check if a variable is defined or not in JavaScript when the target is deep within an object? For example.

// Lets assume this: 
response = {
   status: "simple-message"
}

// running this:
if (response.data.variable_to_check !== undefined) console.log('undefined');
// will result in this:
> TypeError: response.data is undefined

In PHP I can run the equivalent check:

if (!($response->data->variable_to_check ?? false)) die("Handled Undefined Error");
// will result in this:
> Handled Undefined Error

I know I can iterate manually by checking each item starting with the root to see if it's defined, but that seems tedious. That and wrapping everything in a try/catch.

Is there a cleaner / faster / smarter way to do this?

Recognizer
  • 746
  • 1
  • 7
  • 17
  • 1
    https://github.com/tc39/proposal-optional-chaining use babel to emit older javascript equivalents. – ASDFGerte Dec 08 '19 at 04:04
  • 5
    Does this answer your question? [Test for existence of nested JavaScript object key](https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key) – ASDFGerte Dec 08 '19 at 04:06
  • @ASDFGerte, This was what I was looking for, yes. Glad to see it's almost here. And "nested object" was what I was looking for. Couldn't think of the phrase at the time. – Recognizer Dec 08 '19 at 23:19

1 Answers1

0

Use

try{
if(response.data.variable_to_check!==undefined){
console.log("undefined");
}
}
catch(err){console.log(err.message)}
AyushKatiyar
  • 1,000
  • 8
  • 15