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 AJAX Basics (retiring) Programming AJAX Processing JSON Data

How exactly does this script add the property values between the lists tags

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    var employees = JSON.parse(xhr.responseText);
    var statusHTML = '<ul class="bulleted">';
    for (var i=0; i<employees.length; i+=1) {
        if (employees[i].inoffice === true) {

          statusHTML += '<li class="in">'; 
      } else {
          statusHTML += '<li class="out">';
     statusHTML += employees[i].name;
     statusHTML += '</li>';   
   statusHTML += '</ul>';
   document.getElementById('employeeList').innerHTML = statusHTML;

xhr.open('GET', 'data/employees.json');

how does the code above add property values from the JSON to inbetween the lists tags?

1 Answer

Hi there, The key line here is this one:

statusHTML += employees[i].name;

This is where it adds the "name" value from each entry of the employees object, parsed from JSON on the fourth line of code:

var employees = JSON.parse(xhr.responseText);

This line created a JavaScript object from the JSON, which we called "employees". Then, when creating the list, we take each employee's name property and put it between the tags.

statusHTML += employees[i].name;

So "i" here is the index, and this changes with every run through the loop, which means through every run, the value of name will be different and it will be added to a new list item. Am I correct?

That's correct - the loop will increase the index until it is equal to the length of "employees", which will mean they are all printed out.

Thank you for the answer