1

I currently have this global variable declared in javascript.js which I've imported to my main document.

var globalURL = "test URL";

When I try an alert within the javascript.js file it successfully outputs the value of globalURL.

However when I try to an alert with my current document but calling globalURL I get an error

Uncaught ReferenceError: globalURL is not defined 

I'm I doing something wrong here? I followed the example here but still it doesn't work for me. Can I access variables from another file?

UPDATE: I have included my javascript.js file with my current document, so I don't think the error is there. Otherwise the first alert function within the javascript.js wouldn't have run at all.

Community
  • 1
  • 1
user2028856
  • 2,685
  • 7
  • 39
  • 61
  • you need to include the JS file javascript.js in your document before calling the variable. – Pranav Mar 13 '13 at 13:45
  • @Pranav I have included the JS file in my document. Otherwise, my first alert function from within the JS file wouldn't have run if I didn't include it – user2028856 Mar 13 '13 at 13:46
  • As long as `globalURL` is declared first there shouldn't be any problems. You could also remove the `var` keyword which makes the variable global regardless of where it's declared (but it still needs to be declared before use obviously). – powerbuoy Mar 13 '13 at 13:47
  • @user2028856 is your document code in a `document.onready()`? – JamesHalsall Mar 13 '13 at 13:48
  • @user2028856:- check your html in firebug ..whether your script where you are calling the global variable is loaded before or after the external JS file. your script should be loaded after your external JS has been loaded . – Pranav Mar 13 '13 at 13:52
  • Can you show some piece of the HTML rendered..?? – Pranav Mar 13 '13 at 13:53

3 Answers3

1

In your HTML file, you are probably loading the file that you use globalURL before you load the one that sets globalURL

Jeff Shaver
  • 3,095
  • 15
  • 17
0

Open your browser's developer section and there scripts tabs. Observe that both js files are loaded into memory. I believe one of them is not loaded. Global valiarbles in js are available in combined space.

Pompair
  • 6,623
  • 11
  • 56
  • 68
0

Another possibility is that you might be declaring it from inside of a function somewhere. If you want to declare a global variable from inside a function, try leaving off the var at the beginning. This would look like globalURL = "test URL";

ckersch
  • 6,527
  • 2
  • 29
  • 41
  • I wouldn't leave the `var` off. It would probably be better to use `window.globalURL = "test URL";` if anything – Ian Mar 13 '13 at 13:57