0

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?

1
  • 3
    The order matters; scripts are processed top to bottom. Move your index.js below countries.js Commented Jun 8, 2022 at 7:39

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

This is very likely a dupe, right?

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.