Exploring the reach of global arrays in JavaScript

I'm facing an issue while trying to fetch data from a CSV file and store it in an array of objects. Although I understand that global variables are generally discouraged, I'm struggling to find a better way to handle the data and access it across multiple functions.

Here's the snippet of code I have:

let myData = new Array;
$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        let rows = data.split("\n");
        for(let i = 1; i < rows.length; i++){
            let line = rows[i].split(",");
            let obj = {
                index: i,
                img: line[0],
                caption: line[1],
                desc: line[2]
            };
            myData.push(obj);
        }
        console.log(myData); //1
    });
    console.log(myData); //2
    //My goal is to target specific elements on the page and assign attributes based on the objects in my data array, but everything returns as undefined 
});

The first console log correctly displays my data, however, at the second instance, it shows an empty array. I came across this article discussing global variables in JavaScript, which has left me puzzled about what might be going wrong.

Answer №1

The issue with the second part (//2) is that it runs too early in the code execution. When $.get is called, it initiates an HTTP request to fetch the CSV data but does not wait for the request to complete. This is why a callback function like function(data) is necessary. The callback function is only executed after the request is finished, so this is where you should proceed with any further initialization steps.

To address this issue, your code should be structured as follows. If you do not need to store the data globally for other purposes, there is no requirement to use a global variable:

$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        var mydata = [];
        var head = data.split("\n");
        // ...

        console.log(mydata); //1
        continueSetup(mydata); // 2
    });
});

function continueSetup(mydata) {
    // carry out necessary actions here
}

Answer №2

It seems like there may be some confusion with the sequence of events in your code. Utilizing a global variable is perfectly fine, especially if it is being accessed multiple times throughout your page using events or other functions. The reason you are encountering an empty array at position "second" in your code is due to the fact that this specific section (#2) is being executed prior to your get function receiving the necessary data and also prior to step #1.

The function get operates asynchronously, meaning it waits for a response before proceeding with the internal code execution (including step #1). However, section #2 executes immediately while your array remains empty during that initial phase.

Answer №3

When 2 is reached, the data will match the initial value set. However, when 1 is reached, the data will reflect what you have populated.

You may notice that 2 appears first upon observation. This is because the function $.get is asynchronous and runs in the background. The callback provided to $.get will be executed once the GET request is either successful or encounters an error.

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

Guide to sending a socket.io response in a post request using NodeJS

I've got a node server up and running with a React application that's integrated with Socket.io, and everything is working smoothly. However, I also have an external application that relies on the same data. My goal is to post to my node server w ...

Group of Courses - Array feature not filling up properly

Currently, I am in the process of migrating a vb6 program to vb.net. The main objective of the below function is to create a collection of classes. I am using the key as the test_id to access individual classes within the collection in other parts of the p ...

When using JQuery's $.get method and PHP to handle a request with a single quote, the response may contain

I am transmitting data from a client using JavaScript and the jQuery library to a server running on PHP. The data being sent is as follows: From Chrome Dev Tool -> Network Request URL:http://host:8888/RoviImages.php?id=880&aid=334&albumTitle=T ...

.NET Core ViewModel with IFormFile attribute causing AJAX Request to freeze

Users now have the option to upload images for a retail product within an Add/Edit Product modal. Product Modal ViewModel: public class ProductModalViewModel { public ProductModalViewModel() { Product = new ProductDTO(); Images = ...

Typescript - Conditional Type and Optional Arguments

My component has various arguments that can be passed to it: interface Props { label: string; children?: React.ReactNode; withoutActions?: boolean; fieldKey?: KeyProperties; corporate: Corporate; } The withoutActions and fieldKey properties are ...

jQuery - translating and organizing names of countries

I have implemented a jQuery function to organize a list of country names based on the user's selected language code (via a language select dropdown). You can find more information on this topic in this related post. The translation of country names s ...

Adjust the node's location in Cytoscape.js

I recently switched from using Cola to fCose in Cytoscape.js for graphing multiple graphs with no connections. With Cola, I was able to manually set node positions by tweaking the layout options. However, with fCose, despite adjusting variables like quali ...

Mastering the placement of lights in ThreeJS

Struggling for nearly half an hour now, attempting to place a pointlight at the base of my model, but achieving dismal outcomes. Not sure of the dimensions of my model, and consistently failing to accurately pinpoint the light within the scene. Thought ab ...

What is the best way to extract numbers from a string using JavaScript?

I am working with a string in javascript that looks like this: var xyz= "M429,100L504.5,100L504.5,106L580,106L570,98M580,106L570,114"; My goal is to extract the numbers and store them in an array. I attempted the following code: var x=xyz.match(/\ ...

Ways to automatically update ng-class based on changes in ng-model value

I am working on a code where I need to add classes to the 'label' based on whether the input box is empty or not. To achieve this, I am checking if the input box is null and adding classes accordingly. <div class="col-md-12"> <input ...

Is there a way to retrieve the immediate children of all elements using CSS selectors in Selenium?

Although I attempted to utilize the ">" syntax, selenium does not seem to accept it. I am aware that Xpath can be used to obtain what I need, however our project exclusively utilizes CSS selectors. My goal is to create a list containing only the immedi ...

What makes Angular date pickers sluggish?

Have you ever noticed that Angular JS date pickers consume a lot of CPU? When multiple date pickers are present on a page, they can noticeably reduce the site's speed. Is there a way to minimize this issue? Take for example the official Angular for ...

RTL in TextInput only functions properly every other time it is rendered

I am facing a strange problem with RTL where everything seems to be flipped correctly except for TextInput, which only works about half of the time. Check out this gif that demonstrates the issue as I switch between English and Hebrew: (click to view a la ...

Using JavaScript, create a script that will automatically convert the value of an AJAX calendar to a datetime

I am struggling with converting a string into a proper date format using JavaScript in an ASP.net textbox with AJAX calendar extender control. <asp:TextBox ID="tbxReceivedDate" CssClass="selectstyle" runat="server" MaxLength="100" Width="200" onblur="p ...

Creating a nested PHP value object (class)步骤是什么?

I want to implement the following code using class syntax: $result = new stdClass; $result->CategoryListResp->category[0]->categoryId = 1; $result->CategoryListResp->category[0]->categoryName = "Game"; $result->CategoryListResp-> ...

Angular - Dividing Values within Input Arrays

In the input field available to users, they can enter multiple inputs separated by commas. <div class="container"> Enter your values:<input type="text" multiple #inputCheck> <input type="submit"(cli ...

Passing selection from child to parent in ReactJS

When it comes to passing data from parent components to child components, using props is a common practice. But how can data be sent back up to the parent component? I'm working on a set of dropdown menus where users can make selections: DropdownMen ...

javascript issue with attribute manipulation

My current struggle involves setting the attribute of an element through programming, but I keep encountering an error in Firebug: obj.setAttribute is not a function. Since I am working with jQuery, allow me to provide some additional code for better conte ...

Why isn't my function being triggered by the Click event?

I can't figure out why the click event isn't triggering the btn() function. function btn() { var radio = document.getElementsByTagName("input"); for (var i = 0; i > radio.length; i++){ if (radio[i].checked){ alert(radio[i].value); } ...

Having trouble executing the npm start command for ReactJS

Below is the code snippet from my file named server.js if(process.env.NODE_ENV !== 'production') { require('dotenv').parse() } const express = require('express') const app = express() const expressLayouts = require(' ...