How does scope in Javascript work?
- by Jim
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?