14

How do I access a JavaScript array that is defined in another JavaScript file?

1
  • show some code on what you are trying to achieve. Malvolio's answer is correct Commented Mar 9, 2011 at 6:18

4 Answers 4

14

If the variable is global, and you include the JS file with the variable first in your HTML file, then it is accessible via the second JS file:

<script type="text/javascript" src="somefile_with_variable.js"/>
<script type="text/javascript" src="somefile_reading_variable.js"/>
Sign up to request clarification or add additional context in comments.

Comments

5

Inside a browser, all the .js files share the same global space. Just refer to it by name.

Comments

3

Include both files on a certain page and you can access the array normally by its name.

Comments

3

In order for this to work define your array as "var" (global variable). Go to the JS file where the array is and export it.

var globalArray;

export{globalArray, otherFunctionsYouExport};

Now go to the JS file you want the access to the array and import the global array. If you have multiple functions to import, use * and it will export everything between the brackets above.

import * as chooseName from './path of your JS file you export from';

// to use it write this
chooseName.globalArray // put here the rest of your code

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.