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.

6
  • you need to include the JS file javascript.js in your document before calling the variable. Commented Mar 13, 2013 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 Commented Mar 13, 2013 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). Commented Mar 13, 2013 at 13:47
  • @user2028856 is your document code in a document.onready()? Commented Mar 13, 2013 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 . Commented Mar 13, 2013 at 13:52

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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";

1 Comment

I wouldn't leave the var off. It would probably be better to use window.globalURL = "test URL"; if anything
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.

1 Comment

@Pomair yea both the js files are indeed loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.