title: How do global variables work in jquery/javascript? (beginner-level)
body: <p>I basically want to know how global variables work in a javascript/JQuery environment. I am most familiar with a language called <a href="http://processing.org/" rel="nofollow">processing</a> 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. </p>
  
  <p>I have a very simple example made up to illustrate my confusion:</p>
  
  <pre><code> var what="";
  
   $(document).ready(function(){
        $("p").click(function () {
             what="p";
             });
        if(what=="p"){
              alert(what);
             }//end if
   });//end doc ready
  </code></pre>
  
  <p>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".</p>
  
  <p>If someone could explain why this happens, I will be very grateful! </p>