Jim
Jim

Reputation: 19582

How does scope in Javascript work?

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?

Upvotes: 0

Views: 51

Answers (3)

Barmar
Barmar

Reputation: 782508

Javascript scope is by function (ECMAScript 6 adds a let statement that introduces block scope as well). Everything that's not declared using var or function inside a function definition or a let block is in the global scope. There's just one global scope, shared by all <script> blocks. The do block does not introduce a new scope, so the variable declared there is visible in the later document.write().

Upvotes: 4

Adrian J. Moreno
Adrian J. Moreno

Reputation: 14859

In this case, you're creating the variable userName in the global window scope. Once you load your first example into the browser, open the JavaScript console and do a console.log(window). You should see the window object dumped into the console. Open it up and you'll find the key "userName", with the value "George".

When you next reference the variable userName from within document.write, you're referencing it from the global scope.

If instead you had written a function, then called it from document.write(), you would no longer see it in the window scope, so long as you had declared it as a variable local to the function using the var keyword.

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

Upvotes: 1

dehrg
dehrg

Reputation: 1741

The only scope in your example is the global scope. Different script blocks are DOM elements, and do not have their own javascript scope

This is a great reference for javascript scope.

Upvotes: 3

Related Questions