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) jQuery and AJAX Stage 3 Challenge Answer

Using 'this' in .each() loop

Hi,

I am trying to use the 'this' method in my .each() loop for the room widget challenge. Does this make sense? It is working, but I would like to have a second pair of eyes to look at it.

$(document).ready(function() {
  $.getJSON( '../data/rooms.json', function(response) {
    var roomsHTML = '<ul class="rooms">';
    //loop for all the rooms in JSON
    $.each(response, function() {
      //if room is empty or full
      if(this.available === true) {
        roomsHTML += '<li class="empty">'
      }; else (this.available === false) {
        roomsHTML += '<li class="full">'
      };
      roomsHTML += this.room + '</li>';
    }); // end each
    roomsHTML += '</ul>';
    $('#roomList').html(roomsHTML);
  }); // end getJSON
}); // end ready

Thank you for your help!

Zsofia

1 Answer

Assuming everything else is correct. Yes the this property is valid.

However you have a couple syntax errors you'll need to fix.

you have a semi-colon at the end of your if statment and you are missing the word "if" after "else". view below

 //if room is empty or full
      if(this.available === true) {
        roomsHTML += '<li class="empty">'
      } else if (this.available === false) {
        roomsHTML += '<li class="full">'
      };

thank you!

Hey Chyno Deluxe, i am askying myself, if you are right about the missing "if" in Zsofia Helmeczi's code. Because there is no other else following, and the question about the availability of the room is the last question of condition, (since its a boolian, there are only 2 possible conditions) a simple "else" (without "if") should be valid.

From MDN: if (condition) { statement_1; } else { statement_2; }

[EDIT] Oh, i take back all I'v said. I didn't noticed, that Zsofia checked the condition of "available" a second time, which is unnecessary, since its a boolian. And so you are totaly right: Every time a condition is checked, an "if" is mandatory.

Cheers =)