Search code examples
javascriptvariablesundefineduncaught-reference-error

Why is const variable localQuotes not defined in this random quotes generator?


Problem explained more clearly here: I am creating a simple random quote generator using JavaScript. I have hundreds of quotes in an array in a file called "quotes.js" and then the actual function to make it work in a file called "script.js" which are both linked to an "index.html" page. I'm getting the error in my "script.js" page which is supposed to allow a random quote get fetched from the array in quotes.js and display that random quote on the screen with each refresh of the page (you would see the quote in the console and not the actual page yet). Can someone explain to me why I'm getting this error and how to define the variable localQuotes?

This is the error I get in the Developers Tools Console tab in Chrome:

enter image description here

Uncaught ReferenceError: localQuotes is not defined at newQuote (script.js:3) at script.js:7 newQuote @ script.js:3 (anonymous) @ script.js:7

Here is my code from script.js:

function newQuote() {
    const quote = localQuotes[Math.floor(Math.random() * localQuotes.length)];
    console.log(quote); 
}

newQuote(); 

Here is a shorter version of the array in quotes.js:

 const localQuotes = [
 {
    text: 'The greatest remedy for anger is delay.',
    author: 'Seneca',
  },
  {
    text: 'Growth itself contains the germ of happiness.',
    author: 'Pearl Buck',
  },
  {
    text: "You can do what's reasonable or you can decide what's possible.",
    author: null,
  },
];

And then finally my linked JavaScript in the html file:

<!-- Script -->
    <script>src="quotes.js"</script>
    <script src="script.js"></script>


Solution

  • I figured it out. It was in the html tags.

    Instead of:

    <script>src="quotes.js"</script>
    <script>src="script.js"</script>

    It needs to be:

    <script src="quotes.js"></script>
    <script src="script.js"></script>

    SOLVED!