In this article we will be unraveling this mystery so you will know the EXACT differences between these two cases!
Example JavaScript Code
Let's look at the following example JavaScript code. You can run it in Firefox or Google Chrome's console command prompt to see the results of running this code snippet. I put the result of running each console.debug() as a comment right following the line of code.
var v1 = 1; var v2 = 2; var v3 = 3; v4 = 4; v5 = 5; v6 = 6; (function f() { var v1 = 11; v2 = 22; var v5 = 55; v6 = 66; v7 = 77; var v8 = 88; console.debug(v1); // 11 console.debug(v2); // 22 console.debug(v3); // 3 console.debug(v4); // 4 console.debug(v5); // 55 console.debug(v6); // 66 console.debug(v7); // 77 console.debug(v8); // 88 })(); console.debug(v1); // 1 console.debug(v2); // 22 console.debug(v3); // 3 console.debug(v4); // 4 console.debug(v5); // 5 console.debug(v6); // 66 console.debug(v7); // 77 console.debug(v8); // ReferenceError: v8 is not definedThis sample JavaScript code actually demonstrates all eight cases of this situation. In my statements below I assume that variables declared 'globally' are variables defined above f(), and variables declared 'locally' are variables defined within f().
1. A variable is declared with 'var' globally and the same variable is declared with 'var' locally.
2. A variable is declared with 'var' globally and the same variable is declared without 'var' locally.
3. A variable is declared with 'var' globally and the same variable is not declared locally.
4. A variable is declared without 'var' globally and the same variable is not declared locally.
5. A variable is declared without 'var' globally and the same variable is declared with 'var' locally.
6. A variable is declared without 'var' globally and the same variable is declared without 'var' locally.
7. A variable is not declared globally and the same variable is declared without 'var' locally.
8. A variable is not declared globally and the same variable is declared with 'var' locally.
Just by looking at the output of each console.debug() you should be able to figure out what's going on in each case. The follow are points worth noting.
1. It makes no difference to declare a global variable with or without the 'var' keyword.
2. If you declare a local variable with 'var' and the same variable has been declared globally, once you are out of the local scope you'll be accessing the global variable (demonstrated by v1 and v5).
3. If you declare a variable locally without 'var' it becomes a global variable and will be accessible globally (demonstrated by v7)
If you are confused read through the sample JavaScript code again. Eventually you should be able to totally understand each case. If not let me know!