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 Asynchronous Programming with JavaScript Asynchronous JavaScript with Callbacks Managing Nested Callbacks

Managing nested callbacks

const astrosUrl = 'http://api.open-notify.org/astros.json';
const wikiUrl = 'https://en.wikipedia.org/api/rest_v1/page/summary/';
const peopleList = document.getElementById('people');
const btn = document.querySelector('button');

// Make an AJAX request
function getJSON(url, callback) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.onload = () => {
    if(xhr.status === 200) {
      let data = JSON.parse(xhr.responseText);
      return callback(data);
    }
  };
  xhr.send();
}

function getProfiles(json) {
  json.people.map( person => {
    getJSON(wikiUrl + person.name, generateHTML);
  });
}

// Generate the markup for each profile
function generateHTML(data) {
  const section = document.createElement('section');
  peopleList.appendChild(section);
  section.innerHTML = `
    <img src=${data.thumbnail.source}>
    <h2>${data.title}</h2>
    <p>${data.description}</p>
    <p>${data.extract}</p>
  `;
}

btn.addEventListener('click', (event) => { 
  getJSON(astrosUrl, getProfiles);
  event.target.remove();
});

In this code, where getProfile function has been declared, json.people.map calls a callback function with parameter person and that person parameter then accesses the name property of the people object. My question is that person property has not been declared inside the people object so how this function uses this to name property and then links it to name? thanks.

1 Answer

Steven Parker
Steven Parker
210,487 Points

Since JavaScript is a loosely-typed dynamic language, a property can be recognized by name in an object passed into a parameter. Unless you are creating a new object, there's no "declaration" process needed to identify the attributes of an object.

For more details, see the MDN page on JavaScript data types and data structures.

Zoltán Erkel
Zoltán Erkel
6,328 Points

Just wondering, if also the arrow function actually declares the "person" as the parameter of the object? I mean the declaration actually happens when we use the arrow function