Tejas_hooray
Tejas_hooray

Reputation: 636

Can't Access Variable from other Javascript File

I am trying to access a variable from another file in JavaScript, and I'm not able to. When I try to print that variable out, for example, Intellisense suggests the variable. However, when I actually run it, I get the error Uncaught ReferenceError: myVariable is not defined The variable is definitely declared in my file ('homePage.js').

I thought that all variables in Javascript were global, so I'm not sure why this is happening. All my files are in the same folder. Do I need to import something or am I just doing something completely wrong?

Thank you!

Upvotes: 2

Views: 2291

Answers (2)

Gustavo A Olmedo
Gustavo A Olmedo

Reputation: 575

Maybe you are trying to access the variable value when your file still not loaded in the browser. You can check this using window.onload

window.onload = function() {
  console.log('myVariable', myVariable);
  // or execute some function that use the variable
}

https://developer.mozilla.org/es/docs/Web/API/GlobalEventHandlers/onload

Upvotes: 2

Nathaniel Kam
Nathaniel Kam

Reputation: 121

You can also move variables into session state / cookie and pull it back into the other script from there.

Upvotes: 1

Related Questions