0

I have the following random quote generator: https://jsfiddle.net/zachariepertgen/dxnqrkbf/7/

However, I am unable to access the currentQuote variable outside of the quote function.

My goal is to populate the currentQuote variable, so I can later append it to a URL to tweet the current quote.

My understanding is that by declaring the variable outside of the function, I have made it global, and it should be accessible anywhere in my script.

When I call the currentQuote variable to an alert dialog outside of the function I get undefined, however if I call it inside I sucessfully get the quote which leads me to believe it is a scoping issue.

var pickQuote;
var currentQuote;

function quote() {
pickQuote = Math.floor(Math.random() * (quotes.length));
currentQuote = quotes[pickQuote];
document.getElementById('demo').innerHTML = currentQuote;
}

document.addEventListener('DOMContentLoaded', quote, false);
window.alert(currentQuote); `

Please let me know if I am taking a wrong turn somewhere.

Thank you!

Cmdrfluff
  • 1
  • 2
  • 1
    `quote` isn't called until the DOMContentLoaded event fires, which is **after** your `alert`. So naturally `currentQuote` doesn't have a value yet. It will, later, when `quote` is triggered. Move the `alert` (or other handling of the variable) **into** `quote`. (Or use a wrapper event handler that calls `quote` and then shows the the updated value.) – T.J. Crowder Feb 27 '18 at 18:31
  • Side note: If you were using `alert` for testing purposes, beware that it has side-effects which can affect what you're testing. Instead, look for the documentation for the "devtools" (developer tools) for the browser you use for development to see how to debug code in a much more useful way than `alert` provides. – T.J. Crowder Feb 27 '18 at 18:33
  • Also see [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/1541563) – Patrick Roberts Feb 27 '18 at 18:33
  • Thank you! I was unaware I was performing an async call! – Cmdrfluff Feb 27 '18 at 18:34

0 Answers0