Javascript Data Structure Tutorial - Javascript Variable Scope








The scope of a variable is where a variable's value can be accessed.

The scope of a variable in JavaScript is defined as function scope.

A variable's value is visible within the function where the variable is declared and it is also visible within inner/nested functions.

When a variable is defined outside of a function, in the main program, the variable is in global scope.

The global variable can be accessed by any part of a program, including functions.

Example

The following code demonstrates how global scope works:


function showScope() { 
    return scope; 
} 

var scope = "global"; 
console.log(scope);       // displays "global" 
console.log(showScope()); // displays "global" 

The function showScope() can access the variable scope because scope is a global variable.

Global variables can be declared at any place in a program. It can be defined either before or after function definitions.





Example 2

The following code shows the variable shadow:


function showScope() { /*from  w w w.  j a  v a 2s .c  o  m*/
    var scope = "local"; 
    return scope; 
} 

var scope = "global"; 

console.log(scope);       // displays "global" 
console.log(showScope()); // displays "local" 

The scope variable defined in the showScope() function has local scope, while the scope variable defined in the main program is a global variable.





Without var keyword

JavaScript can define variables without using the var keyword.

In that way the the variables has global scope, even if the variable is defined within a function.

The followng code demonstrates defining variables without using var keyword.


function showScope() { /* w  w  w.  j  a va 2s . com*/
    scope = "local"; 
    return scope; 
} 

scope = "global"; 
console.log(scope);       // displays "global" 
console.log(showScope()); // displays "local" 
console.log(scope);       // displays "local" 

Because the scope variable inside the function is not declared with the var keyword, when the string "local" is assigned to the variable, we are changing the value of the scope variable in the main program.

Note

JavaScript has function scope. This means that JavaScript does not have block scope.

With block scope, you can declare a variable within a block of code and the variable is not accessible outside of that block, as you typically see with a C++ or Java for loop:

for (int i = 1; i <=10; ++i) { 
    cout << "Hello, world!" << endl; 
} 

Even though JavaScript does not have block scope, we can still write for loops as follows:

for (var i = 1; i <= 10; ++i ) { 
    console.log("Hello, world!"); 
}