2

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!

Tejas_hooray
  • 606
  • 1
  • 6
  • 16
  • In javascript, you can't access a variable from a different file until they are linked. Have you linked those two files? – doc-han Jun 06 '20 at 00:35
  • @Doc-Han Thanks for responding! I haven't, how would I do that? Sorry, I'm a complete newb at Javascript. – Tejas_hooray Jun 06 '20 at 00:36
  • Read from here https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file Or here too https://hype.codes/how-include-js-file-another-js-file – doc-han Jun 06 '20 at 00:39
  • @Doc-Han I'm not using Node.js or Jquery, would this still work? – Tejas_hooray Jun 06 '20 at 00:42
  • JavaScript runs either on the web or on a server(node.js) so in order to connect two js files, you have to be on one of these environments. If on the web you can connect them using an HTML file – doc-han Jun 06 '20 at 13:28

2 Answers2

2

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

Gustavo A Olmedo
  • 565
  • 4
  • 13
1

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