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

Basic Scoping Issue? What am I missing?

Hi all! I made a very simple program for an ajax request that should log the JSON array to the console.

var studentListData;

var request = new XMLHttpRequest();
request.onreadystatechange = function () {
  if (request.readyState === 4) { 
    studentListData = JSON.parse(request.responseText);
    };
  };
request.open('GET', 'ajax.json');
request.send();

console.log(studentListData);

The XML request works ok, but the console.log() method returns "undefined", even though when I input "studentListData" to the console it returns the entire array. Kind of maddening-- I know I am missing something rudimentary :-( Thanks in advance for your help!

2 Answers

Does the AJAX call execute then the code underneath it? I bet it works also if you put the console.log line in a "call back" (after AJAX call is executed). I can't wait to get up to the asynchronous stuff on the JS track.

Yeah, read an article about variable scope and callbacks-- seems that scope gets kind of funky with callbacks. Wrapped the whole AJAX call in a function then passed console log as a callback. Seemed to work 🤷‍♂️

Comment-out the console.log line and copy it here instead (inside if-block). This should also test that the if-condition is true, being executed.

studentListData = JSON.parse(request.responseText);
console.log(studentListData)
};

Let us know if this helps!

Yup, it definitely works that way, but I am wondering why it will not console studentListData when outside the the if-statement. Since I defined the variable outside the scope of the if-statement on line one, shouldn't it console studentListData on the final line of the code?