I’m struggling with (what I believe to be) a scoping issue. Here’s a sample of my code:
$(document).ready(function() {
var counter = 0;
function scrollTweets() {
counter ++;
// rest of code
}
...
)}; // end of document ready
When I look up the variable counter in Chrome’s Javascript console it returns “ReferencedError”. However, when I remove var from the code above and type counter into the console, it returns the value. Why is this?
I think understanding this simple concept would allow me to tackle issues that seem to pop up during development. Is it just a scoping issue on Chrome’s part? Am I needlessly wrapping everything in the $(document).ready “function”?
The
varlocks the variablecounterinto whatever the lexical scope is — which means its available in the current block, method, whatever, and can be attached to closed-in scopes (ie. closures), like you are doing withscrollTweets. Socounteris only available in thereadycallback and anything that has a closure around it, which is why you can’t access it from your console.When you take the
varaway,counteris effectively global, which is why you can access it in that case.