-2

I have an object that returns properties that are either defined or undefined.

I wish to handle these undefined properties but I keep getting an error of undefined. The following two code snippets below are what I have tried so far:

if (typeof choice.Location == "undefined") {
}

and

if (choice.Location == undefined) {

}

Edit:

To clarify, if I do something like this.

if (typeof choice == "undefined") {
}
else if (choice.Location) {
//do something 
}

I get the same error.

sacora
  • 265
  • 1
  • 3
  • 8

1 Answers1

1

You can check for both the object and then it's property.

Something simple like the following would do it:

if (typeof choice !== 'undefined' && choice.location) { ... }
Dimitrios Matanis
  • 896
  • 1
  • 6
  • 19
  • This doesn't work for me. It gives me the same error. – sacora May 30 '18 at 12:33
  • 2
    @sacora If you want help then please read how to create a **[mcve]**. You must post some code that we can run so that we can actually see the problem, because the answers you have been given *are correct*, so your question must be wrong. Until we can reproduce the problem then you have not asked a valid question. Please don't reply to this comment. Just digest, read the link I've given you, and then fix the question or ask a new one. – Reinstate Monica Cellio May 30 '18 at 12:35
  • I agree with Archer but i've updated my answer to include a typeof comparison. I'm not sure what you are trying to do exactly, but this solution should work for most cases – Dimitrios Matanis May 30 '18 at 12:42
  • If my updated answer works for you, do you mind accepting it please? – Dimitrios Matanis May 31 '18 at 09:03