mardi 27 février 2018

Unable to use pre-definded global variable outside function [duplicate]

This question already has an answer here:

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!




Aucun commentaire:

Enregistrer un commentaire