Ask coding questions

← Back to all posts
How do change global variables in a function js?
ShivankChhaya (241)

Hi.

In the user.html file, it should be displaying the user's avatar, and for that, it needs to change the global variable inside a function. The fucntion is being called, however, the variable is not changing! Could someone help me with this?

Comments
hotnewtop
ShivankChhaya (241)

Sorry I didn't mention this, but h was used for debugging, and isn't actually part of the actual project(Maybe obvious).

Coder100 (18903)

The reason is because remember: process isn't guaranteed to be finished when you do that alert function.
The alert function gets called, which probably prints fgf because the process function hasn't been finished yet, and then the variable gets set in process. So that means all other code that depend on h will need to be in the process function.

ch1ck3n (2359)

@Coder100 i would like to add

use fetch instead so when the request is finished you can run the code without all of the messy XML api

Coder100 (18903)

but that's their choice @ch1ck3n

ShivankChhaya (241)

@ch1ck3n I think i'll go with fetch

ShivankChhaya (241)

@Coder100 the thing is, h isn't part of the project itself. It was used for debugging when i got really frustrated. userdict is the real global variable here, and the entire program depends on userdict. You think there's a way to do what i need without putting the code in the process function?

Coder100 (18903)

@ShivankChhaya well if you used fetch you could put it all in an async function

(async () => {
  let data = await fetch(...).then(r => r.(...)());
  // use data freely
})();
ch1ck3n (2359)
      function process(e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
          response = JSON.parse(xhr.responseText)
          h = 'rfr'
        }
      }

uhhh why did you add window

Coder100 (18903)

because window is global @ch1ck3n

ShivankChhaya (241)

@ch1ck3n i looked at websites, got frustrated, added window, that didn't work so then i posted the question on replit.