Variable Scopes in Javascript


Many articles have discussed the variables scopes in Javascript. Today, I will explain it during my own experiments.

The javascript has only two scopes, local or global. It does not have nested block scopes, which makes it easier to learn.

The most important keyword when coming to the variable scope, is the ‘var‘. If you define variables outside functions, it will be global whether you add ‘var‘ or not.

However, inside a function, the ‘var’ keyword is required to define variables that have the local scope only. Otherwise, the system will look through each levels up and use them if they are defined. If not, eventually a global variable will be defined. That is why it is very important to define var in functions if you intend local variables only.

Another interesting fact is that if you define var in functions, but you use it earlier (e.g. before the declaration), it will be treated as they are local variables, although they have share the name as other global variables.

The full example is given below, which has passed the tests under Win7, 64-bit, Window Script Hosting environment.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* https://justyy.com
 Tested under Windows 7, 64-bit
 Windows Scripting Host
*/
 
var ws = new ActiveXObject("WScript.Shell");
 
// the following two are both globals
var global1 = "global1";
global2 = "global2";
 
function fun1()
{
    ws.popup(global1); // global1
    ws.popup(global2); // global2
    var local1 = "local1";
}
 
fun1();
// ws.popup(local1); // undefined.
 
function fun2()
{
    ws.popup(global1); // undefined
    var global1 = "local";
}
 
fun2();
ws.popup(global1); // global1
 
function fun3()
{
    global3 = "new";
}
 
fun3();
ws.popup(global3); // new
/* https://justyy.com
 Tested under Windows 7, 64-bit
 Windows Scripting Host
*/

var ws = new ActiveXObject("WScript.Shell");

// the following two are both globals
var global1 = "global1";
global2 = "global2";

function fun1()
{
	ws.popup(global1); // global1
	ws.popup(global2); // global2
	var local1 = "local1";
}

fun1();
// ws.popup(local1); // undefined.

function fun2()
{
	ws.popup(global1); // undefined
	var global1 = "local";
}

fun2();
ws.popup(global1); // global1

function fun3()
{
	global3 = "new";
}

fun3();
ws.popup(global3); // new

Happy Scripting!

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
323 words
Last Post: Execute External Programs, the Python Ways.
Next Post: Dis Module in Python

The Permanent URL is: Variable Scopes in Javascript

Leave a Reply