Javascript variable scope

let preGameRequest = new XMLHttpRequest();
let preGameData;

preGameRequest.open("GET", "/matches/live.json");
preGameRequest.onload = function() {
    preGameData = JSON.parse(preGameRequest.responseText);
}
preGameRequest.send();
console.log(preGameData);   // issue arises here

I've encountered a problem with my code. I declared preGameData as a global variable and attempted to store the data from the '/matches/live.json' file into it. However, when I attempt to log preGameData outside of its scope (like in the code section), it returns 'undefined'. Strangely enough, logging preGameData from within the scope works perfectly fine. I'm quite puzzled by this behavior and unsure of what exactly is causing it.

Answer №1

Here's a revised version of the code that should function correctly:

preGameRequest.onload = function() {
    preGameData = JSON.parse(preGameRequest.responseText);
    console.log(preGameData);
}

The key explanation: is due to the fact that the preGameRequest.send() function operates asynchronously.

When the console tries to run console.log() (as shown in your example), the HTTP response has not been received yet, resulting in the variable being undefined.

However, by placing console.log() inside the handler function (like in my provided example), it will execute only when the response is fully received (within the onload() handler). This ensures that the variable preGameData will be defined and accessible at that point.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I locate a Forum or Node using a JWT Token as a reference point?

Could someone please guide me on locating my forum using my JWT token? exports.getByOwnerID = function (req, res, next) { Forum.find({createdBy: req.body.createdBy}) .then(doc => { if(!doc) { return res.status(400).end();} return res.sta ...

Arranging based on the initial elements of the array

Could I please receive the arrangement ['H','H','A','A'] from the given input ['H','A','H','A'] Is there a way to organize it according to the first occurrence of each charact ...

Checking phone numbers in JavaScript utilizing regular expressions while retaining the same keypress functionality

Using regular expression in JavaScript, validate a phone number with functionality similar to keypress. $('#phone').keypress(function(e) { var numbers = []; var keyPressed = e.which; for (var i = ...

Incorporate JSON data into a JavaScript search in CouchDB

I am currently working with a CouchDB database that contains approximately one million rows. My goal is to query for specific rows in the database using the keys provided in an external JSON file. The approach I am currently using to achieve this involves ...

Display 'Div 1' and hide 'Div 2' when clicked, then reveal 'Div 2' and hide 'Div 1' when a different button is clicked

I need help figuring out how to make two separate buttons work. One button should display 'Div 1' and hide 'Div 2', while the other button should show 'Div 2' and hide 'Div 1' when clicked. My knowledge of jquery an ...

Implementing Yii pagination with asynchronous loading

Can anyone help me enable pagination using Ajax in my code? I have a Controller that updates content via Ajax. function actionIndex(){ $dataProvider=new CActiveDataProvider('News', array( 'pagination'=>array( ...

Inconsistent Accuracy of React Countdown Timer

Hello everyone! I'm new to programming and I'm currently working on creating a countdown timer that goes from 3 to 0. The issue I'm facing is that the timer counts down too quickly when rendered on the screen. I've tried adjusting the i ...

What could be causing the error message to appear stating that each list item must have a unique key when utilizing react-bootstrap in Nextjs?

My file currently contains keys for each child component, but it is still raising an error internally. I am unsure if I can resolve these issues on my own. export default function SecondaryNav(props:NavItems) { const router = us ...

Avoid printing employees whose ID begins with special characters

My C# API sends all employee information from the database to my Angular web app. I need to filter out employees with IDs starting with '#' in Angular. Employee = Collaborator Below is the Angular service code that calls the API to fetch the d ...

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

Properly Adding an External jQuery File in HTML Using jQuery

Seeking assistance as a newcomer to JS and programming in general. Currently working on a website where each page has its own HTML / PHP file, with jQuery and global JS functions included in the footer via a separate includes file "footer.php". Everything ...

Enhancing nested data in Firebase

According to the information from the Firebase note: When using a single key path such as alanisawesome, the updateChildren() method will only update data at the first child level. Any data passed in beyond the first child level will be treated as a setVa ...

What is the process for configuring Nock.js to respond with the posted data?

Consider the following function: createTrip: function(trip, userId) { trip.userId = userId trip.id = uuid() return axios .post(`${url}/trips`, trip) .then(res => res.data) .catch(error => error) } Now let's take a look at thi ...

Is the server's performance improved by routing through Angular instead of using Express for routing?

I'm currently working on developing a web application and I've been thinking about using client-side JavaScript (Angular) for routing. I believe that by routing through Angular, it could potentially speed up my application by reducing the number ...

The construction of the Gatsby site encountered a major obstacle

I've been facing challenges while trying to build my Gatsby site. Whenever I run 'gatsby develop' in the console, my app starts without any issues. However, when I attempt to build it, I encounter errors like the ones shown below. Does anyon ...

JavaScript functioning exclusively for specific list items within an unordered list

After implementing JavaScript on my website, I noticed that it only works when clicking on certain list items (li's) and not on others. Specifically, the functionalities for Specialties, Contact Us, and Referral Schemes are not working correctly. ...

How to visually deactivate a flat button ( <input type="button"> ) programmatically with JavaScript

I am facing an issue with my buttons. I have one regular button and another flat button created using input elements. After every click, I want to disable the buttons for 5 seconds. The disable function is working properly for the normal button, but for th ...

Transformed the Next.js Pages Router into an Application Router

Looking to make a change in my API written with Nextjs's Pages Router. Currently, it serves as a proxy for downloads and I am interested in converting it to the App Router method. Does anyone have any guidance on how to go about implementing this? imp ...

Design nested divs that can be dragged within the confines of their parent div

At first, the app will include a single button called AddParent located at the top. When the user clicks the AddParent button, a parent draggable component is added to the existing component. This means that every time the button is clicked, a new parent ...

Customizing external elements with React's inline styling feature

Trying to use React to style elements generated by a third-party library has been a challenge. In the snippet below, I was able to achieve the desired styling using CSS, but now I am looking to accomplish the same using JavaScript. This way, users can defi ...