How does scope in Javascript work?

Posted by Jim on Stack Overflow See other posts from Stack Overflow or by Jim
Published on 2014-08-22T21:59:56Z Indexed on 2014/08/22 22:20 UTC
Read the original article Hit count: 235

Filed under:

I can not understand how scoping works in Javascript.
E.g.

<html>  
  <head>  
    <script>var userName = "George";  </script>
  </head>
  <body>  
     ......  
     <script>  
        document.write('Name = ' + userName);  
     </script>  
  </body>   
</html>   

The variable userName is declared in another "section" of a script. As I understand it the browser renders html and executes code in the order it finds it. So how does userName in the second script tag gets resolved? Does it go to a global setting? Anything I declare earlier is global?
I noticed the same happens if I do something like:

<html>  
  <head>  
    <script>  
          do {  
              var userName = "George";   
              //bla  
          } while (someCondition);  
    </script>
  </head>
  <body>  
     ......  
     <script>  
        document.write('Name = ' + userName);  
     </script>  
  </body>   
</html>     

Even when userName is declared inside {} it is still resolved in the second script. How is that possible?

© Stack Overflow or respective owner

Related posts about JavaScript