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

Michal Bednář
Michal Bednář
9,415 Points

Need to clarify this

Hi guys, I want to ask you about the code down bellow:

$(document).ready(function () { 
  var url = "../data/employees.json"; employees.json

  $.getJSON(url, function ( response ) { 
    var statusHTML = "<ul class='bulleted'>";
    $.each(response, function(index, employee) {
      if ( employee.inoffice === true ) {
        statusHTML += "<li class='in'>";
      } else {
        statusHTML += "<li class='out'>";
      }
      statusHTML += employee.name + "</li>";
    });
    statusHTML += "</ul>";
    $("#employeeList").html(statusHTML);
  }); // end getJSON
}); // end ready

I am basically understanding whole code besides these:

  $.getJSON(url, function ( response ) { 

What does the "response" in this case mean? What is happenning with it?

My another question is about this line:

$.each(response, function(index, employee) {

Why do I have to put "response" in the .each() function? And actually why "employee" on the 2nd place?

I know these questions are kind of silly, I just can't wrap my head around it.

Thank you a lot, have a great day.

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

Check out the jQuery .getJSON() docs for the best explanation.

Basically response is just the variable name given (defined by you) to the to the data you are receiving - the "response data" you requested. So, you can name/declare it anything you want.

Now when you want to loop through the response data you do the .each() with your "response data" which in this case is called response - of course you have to use a declared variable, that's why they must match.

response is to the anonymous function on .getJSON() as index and employee is to the anonymous function in the $.each()

Hope that makes sense.