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 Programming AJAX Processing JSON Data

Robert Bourton
Robert Bourton
6,179 Points

Is this cleaner/easier to read?

I just wanted to rewrite some of the code my way, looking for ways to make it easy to maintain and to update.

How would you rewrite this code in this video?

  • looking for clean code
  • easy to read
  • maintain in the future
  • pure JavaScript
getJSONRequest((html) => {
  const container = document.querySelector('#employeeList')
  container.innerHTML = html
})


function getJSONRequest(cb) {
  const xhr = new XMLHttpRequest()
  let html = '<ul class="bulleted">'

  xhr.onreadystatechange = function () {

    if (xhr.readyState === 4) {
      const employees = JSON.parse(xhr.responseText)

      for ( const employee of employees) {
        html += createHTML(employee.inoffice, employee.name)
      }

      html += '</ul>'
      cb(html)
    }
  }
  xhr.open('GET', 'data/employees.json')
  xhr.send()  
}

function createHTML(inoffice, name) {
  return `<li class=${ inoffice? "in":"out" }> ${name} </li>`
}