Programming Language

In Javascript, What Is Function Scope?

Although there is an absence of Black Scope in Javascript, however, it comprises of function scope. This term means that all the variables that are declared inside a function can be seen in the whole function in which they have been defined; it does not matter that those variables are declared if statement, for loop, inside a while loop, or some other block of code inside that function. The nested functions (which are actually the functions declared inside other functions) can even view and access variables that are declared in their enclosing, outer function(s). The best way to illustrate the function scope is by using an example.

  • Function Scope in Javascript Example

function scopeTes() {

var x = 4;

//this will be true always:

If (x == 4)

{

var y = 30;

for (var i = 0; i <= 10; i++)

{

var inFor = i;

}

}

(z) console.log; // z is described, 30 prints

(j) console.log; // j is described, 12 prints

(inFor) console.log; // in For is described, 10 prints

}

Now from the above example, you can clearly see that the variables inFor, z and j are declared either inside the for loop or inside the if statement. However, those variables, are still visible to the remaining functions, even after being declared within those separate blocks. This is all because of those variables that are declared within one function. This is exactly what function scope is actually about.

Below is another demonstration that how Javascript can use function scope. In this example, a nested function can view and access variables that are declared in its enclosing, outer function.

  • Nested Functions Can See Variables Declared In Their Enclosing Functions

ScopeTest function() {

variable x = 4;

/* however is a nested function

as it has been defined under

scopeTest

*/

function nested ( )

{

/* this is going to output 4 as the variable x is visible

although it has been declared under

scopeTest- the outer function */

alert(x);

}

// call to the nested function

nested();

}

// call to the outer function

scopeTest( );

In the above example, you can see that the nested function has access to the variable “x” of outer function. And because of this fact, the above code will output “4”. The reason behind this is that the Javascript uses function scope and here variables that are declared within a function can be seen even inside the nested functions.

 

Leave a Reply