I basically want to know how global variables work in a javascript/JQuery environment. I am most familiar with a language called processing which I've been told is java-based. I expected variables in javascript and JQuery to behave like the ones in processing, but they do NOT work as I expect and I cannot for the life of me wrap my head around it.
I have a very simple example made up to illustrate my confusion:
var what="";
$(document).ready(function(){
$("p").click(function () {
what="p";
});
if(what=="p"){
alert(what);
}//end if
});//end doc ready
In processing, this would work because the 'what' variable is global and as it is changed by clicking on a paragraph, the if statement should be continuously checking to see if 'what'=='p', and trigger the alert. But that is not what happens-- 'what' only seems to be updated WITHIN the click function, even though it is a global variable, so when it comes to the if statement, 'what' still equals "" instead of "p".
If someone could explain why this happens, I will be very grateful!