13

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

EJZ
  • 1,142
  • 1
  • 7
  • 26
Deepa
  • 1,201
  • 5
  • 15
  • 23

4 Answers4

13

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"/>
Dolan Antenucci
  • 15,432
  • 17
  • 74
  • 100
5

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

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
3

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

Ghyath Serhal
  • 7,466
  • 6
  • 44
  • 60
2

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
Shiran .Y.
  • 33
  • 4