0
typeof(nonexistingobj)

returns 'undefined' BUT

typeof(nonexistingobj.nonexistentproperty) 

does not generate 'undefined' as I was expecting, but something called a Reference Error - how do I detect this?

I'm trying to do sub-property detection on the response from an API. (Specifically, the API returns a sub object called data.paging.next when there's another page of API results to get, but no 'next' sub object if it just returned the last page).

3
  • 1
    You get a ReferenceError when trying to reference a property on an object that does not exist. So in your case, obj does not exist (so it's undefined). You can detect this by checking "undefined" === typeof(obj) Commented Jun 23, 2013 at 16:47
  • 1
    typeof is an operator, not a function. You use it like typeof obj.nonexistentproperty. Commented Jun 23, 2013 at 16:48
  • 1
    You can detect a ReferenceError by wrapping your call in a try-catch statement Commented Jun 23, 2013 at 16:49

2 Answers 2

3

Don't try to access a property of undefined. Test if the variable you are trying to access is defined first.

if (typeof obj !== "undefined") {
    typeof obj.nonexistentproperty;
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhh, that does it. Thanks.
0

To catch errors you can use try/catch:

try {
     console.log(typeof nonexistingobj.nonexistentproperty);
} catch (error) {
     console.log('Message error: ' + error.message);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.