Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Michal Bednář
Michal Bednář
9,414 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,822 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.