What is Function Scope in Javascript?

Although Javascript does not have Block Scope, it does have what is known as function scope. Function scope means that any variables declared inside a function will be visible in the entire function in which they are defined, regardless of whether those variables are declared inside a while loop, for loop, if statement, or some other block of code within that function. Even nested functions (which are basically functions declared within other functions) can access and view variables that are declared in their outer, enclosing, function(s).

As always, the best way to demonstrate function scope is with an example:

Example of Function Scope in Javascript

function scopeTest() {

var x = 2;

//this is always true:
if(x == 2)
  var y = 15;
  for (var i = 0; i <= 5; i++)
    var inFor = i; 

  console.log(y); // y is defined, prints 15   
  console.log(i);  // i is defined, prints 6
  console.log(inFor);  // inFor is defined, prints 5

You can see in the code above that the variables y, i, and inFor are declared either inside the if statement or inside the for loop. But, even though those variables are declared inside those separate "blocks", they are still visible to the rest of the function. This is because all of those variables are declared inside one function - which is what function scope is all about.

Here's another example of how Javascript uses function scope - a nested function can access and view variables that are declared in it's outer, enclosing function.

Nested functions can view variables declared in their outer functions

function scopeTest() {

var x = 2;

/* this is a nested function
    because it is defined inside another
    function - scopeTest
function nested ( )
  /* this will output 2 because the nested function can
  see the variable x even though it is declared inside 
  the outer function scopeTest */ 
  // call to the nested function

// call to the outer function
scopeTest( );

You can see in the code above that the nested function will have access to the outer function's variable "x". And the code above will output "2" because of that fact. This is all because Javascript uses function scope - where variables declared within a function are visible even within the nested functions.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

One thought on “Javascript Function Scope”