9

I defined a variable in one of my JavaScript files. I want to access the value of that variable among JavaScript files. In one file I am initializing the value of that variable.

I cannot access the assigned value in another JS files.

Is there anything that I am missing ?

1
  • can you show us how you declared it? and where exactly Commented Oct 26, 2010 at 10:07

3 Answers 3

10

You should be able to access them if they are in the global scope or can be accessed from the global scope.

For example, I have a object literal like this in my HTML in a script element...

<script type="text/javascript">
    var config = {
       basePath: '/path/'
    };
</script>

Which I can access in any other subsequent JavaScript file with config.basePath.

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

3 Comments

Can this be in a separate js file? I have tried this, and I cannot seem to get it working. I get, Uncaught ReferenceError: config is not defined
@diek You will need to research JS scoping, but yes it's possible to be a in a different file.
hey alex, thanks I actually went with a different approach. But I did get yours to work as well.
9

It has to be a global variable, or accessible in the same scope (e.g. a property on something else that's global), and it has to be defined before you're accessing it, meaning the order of your script includes matters.

You can't for instance have this in one file:

(function() {
   var something = "blah";
})();

...and access it in the next file, since that variable is scoped to that function.

Comments

6

also, once globally defined, you might need to be accessing it via the window object like this: window.your_variable OR window['your_variable']

Comments

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.