Skip to content

Try to avoid global variables #23

@oliverjam

Description

@oliverjam

Using global variables can cause problems, especially with async code. If you update a global variable after a promise resolves (i.e. inside the .then or after an await) then other code that executes synchronously might not see the correct value. E.g.

let data = null;
fetch("example.com").then(response => {
  data = response;
})
console.log(data);

Here data will be null since the promise won't have resolved before the log runs. This gets more complicated with event handlers etc since the promise might have resolved, but you shouldn't rely on this. The only time you should access the results of asynchronous code is inside the .then (or after the await).

In this app I'm not sure you are actually using the global variables outside of the functions where you fetch them, so you could probably just refactor to only have locally function-scoped variables. In general functions should take input and return output and have no effect on the outside environment (this is known as "pure functions").

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions