Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) Programming AJAX AJAX Callbacks

James Barrett
James Barrett
13,253 Points

Why are we using a nested if statement for the HTTP response?

I am confused as to why Dave has used a nested if to check if the HTTP response was 'OK'. Why couldn't the && operator be used?

Thanks, James.

2 Answers

jsdevtom
jsdevtom
16,963 Points

tl;dr: DRY coding

He did this so that after xhr.readyState === 4 (request finished and response is ready) Then he can check for request errors such as 404.

I think he could have done this:

var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("ajax").innerHTML = xhr.responseText;
  } else if (xhr.readyState == 4 && xhr.status == 404) {
    //throw error
  }

But that would take more code because he is checking for xhr.readyState == 4 every time instead of just once.

Sean T. Unwin
Sean T. Unwin
28,690 Points

If you notice in the video, roughly between the 2 - 4 minute marks, Dave is using '&&'. However, he discusses about checking for other specific status codes. The error handling via the if else statements are specifically dealing with status codes.

Issues would possibly, and likely, arise if those error handling statements were attached to the top level if statements because using ' && ' means " if both conditions are true then continue ", where 'both conditions' is referring to those before and after the ' && '. Logically, the if else statements, should be dealing with both of those conditions were false.

The case here is solid because first, we don't want to do anything until the server is finished communicating, i.e. readystate. Once that confirmation has been made we then want to, broadly, verify that the data received is what the server believes we wanted, i.e. there has been no error retrieving and sending the data. At this point we also want to handle issues for when there are errors accessing the data which was requested.

readystate has to do with the request to have a conversation with the server - the hello and goodbye portion, if you will. status is dealing with the server's ability to do something about our request.

tl;dr: the corresponding if else statements have to deal with status codes only, not readystate codes so the logic of our conditionals should reflect that.