Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript accessing a variable in a different file

So i am trying to access an array in index.js a different file called countries.js. However when i check the console it says that countries is not defined?

index.js

countries.includes('Ethiopia') ? console.log('ETHIOPIA') : countries.push('Ethiopia')

countries.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 const countries = [
    'Albania',
    'Bolivia',
    'Canada',
    'Denmark',
    'Ethiopia',
    'Finland',
    'Germany',
    'Hungary',
    'Ireland',
    'Japan',
    'Kenya'
  ]

index.html

<body>
    <script src="index.js"></script>
    <script src="countries.js"></script>
    <script src="web_tech.js"></script>
</body>

All the scripts are in the index.html so im stuck as to why i cant access the variable?

>Solution :

At the time you are executing code in index.js the countries variable does not exist yet. You need to create the variable before using:

<body>
    <script src="countries.js"></script>
    <!-- Now "countries" exist for index.js to use -->

    <script src="index.js"></script>
    <script src="web_tech.js"></script>
</body>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading