0

i am now learning javascript and found some problems with this code

var response = '{"status":{"message":{"-1":[111]}}}';
response = jQuery.parseJSON(response);
if ( typeof (response.status.warning[-1]) == "undefined" ) {
    console.log(true);
};

why he throws a error, instead of just ignoring "console.log" part?

dafuq is this javascript

1
  • try change response.status.warning to response.status.message Commented Mar 6, 2013 at 8:02

2 Answers 2

2

You need to code this more defensibly:

if (response && (!response.status || !response.status.warning || typeof (response.status.warning[-1]) == "undefined" ) {

Checking the existence of response.status and response.status.warning should be done. If response.status doesn't even exist, response.status.warning will generate an error

Sign up to request clarification or add additional context in comments.

4 Comments

Is there possibility to avoid printing object to console if "if" statement is false, without adding "else" ? i.sstatic.net/m3WNC.png
Update, object was printed only if u run script in console, tried on "live", everything is ok.
So does that mean it worked? Or are you still having problems?
I am checking my monitoring service, if until 18:00 i will not notice this error again, i will check your answer as a solution :)
1

Because it can't even get through this part:

typeof (response.status.warning[-1]) == "undefined" 

since response.status.warning is undefined. That's why it throws an error.


To check if response.status.warning exists only when you are sure that response and .status are not undefined:

if(response.status.warning){
    console.log("It exists!");
}

6 Comments

I ve changed message to warning on purpose, i want to check what will happens if in response will be no "message"
@Nerfair response.status.warning == undefined will check if it exists or not.
Javascript doesn't like to access properties of undefined objects. that's why you should always make it a habit to check for the existence of the property before you access it. The other answer covers this point.
@sweetamylase - But since it is jQuery then response and .status should always exist according to the doc.
Irrelevant in this case, See in his example, he's converting the string '{"status":{"message":{"-1":[111]}}}' into JSON object.
|

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.