0

I am making an api call where a property may or may not exist. My first thought was wrapping that in a ternary statement would fix this issue, however, it is not.

 newObject.fax_from      = value.from.phoneNumber  === 'undefined' ? 'none' :  value.from.phoneNumber;

When the property this not exist in the api return data, I get a message that

TypeError: Cannot read property 'phoneNumber' of undefined

any ideas?

I even tried to be more specific such as

 newObject.fax_from      = value.from.phoneNumber = typeof( value.from.phoneNumber) == 'undefined' ? 'none' :  value.from.phoneNumber;
chewie
  • 529
  • 4
  • 17
  • 1
    The error says `from` is undefined. Use `value.from?.phoneNumber`. Also, you are adding quotes around `undefined`. It should either be `a === undefined` <-- without quotes or `typeof a === 'undefined'` <-- because typeof returns a string – adiga May 24 '21 at 10:45
  • `value.from.phoneNumber === 'undefined'` looks to see if it has the value `"undefined"` (a string). `undefined` is just `undefined` (no quotes). Also, it would appear that `value.from` (not `value.from.phoneNumber`) is what's `undefined`. In modern environments you can use optional chaining and nullish coalescing: `newObject.fax_from = value.from?.phoneNumber ?? "none";` In older environments, probably `newObject.fax_from = (value.from && value.from.phoneNumber) ? value.from.phoneNumber : "none";` if you also want to use `"none"` when `value.from.phoneNumber` is a blank string. – T.J. Crowder May 24 '21 at 10:46
  • @T.J.Crowder yea, I tried undefined with no quotes as well, and the same result. – chewie May 24 '21 at 10:47
  • @T.J.Crowder this actually worked `value.from?.phoneNumber ?? "none";` that was odd, any reason as to how that is working? – chewie May 24 '21 at 10:50
  • @chewie - See [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) and [nullish coalescing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator). – T.J. Crowder May 24 '21 at 10:53

0 Answers0