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
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?
Advertisement
Answer
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>