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

Time:11-19

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(); 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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,
  },
];
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

And then finally my linked JavaScript in the html file:

<!-- Script -->
    <script>src="quotes.js"</script>
    <script src="script.js"></script>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your quotes.js will need to give global access to the variable for it to work. This is how you should do it:

window.localQuotes = {...}

Oh and your script tag is wrong, you have a typo there, I expected it to be a typo when writing the question so if it still doesn't work, fix that typo.

CodePudding user response:

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

Instead of:

<script>src="quotes.js"</script>
<script>src="script.js"</script>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

It needs to be:

<script src="quotes.js"></script>
<script src="script.js"></script>
<iframe name="sif5" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

SOLVED!

  • Related