JavaScript Scopes And Closures

In this post we will learn about JavaScript Scopes And Closures. In JavaScript functions and objects are also variables. A scope is a term which is used to define a region in source code. In this region a variable can be defined and accessed without any errors. In JavaScript scope is a Lexical Scope or Static Scope.

JavaScript has two types of scopes

  • 1) Global Scope: Once an variable defined in Global scope than can be accessed and modified anywhere even within different program files. For example
    var my_app = appName(); // define a variable which store string return by function
    
    /**
    * This function will return the appName
    * @return string
    */
    function appName()
    {
    return 'OsinLab Application';
    }
    
    console.log(my_app);

    or you can assign the value to this variable in the below way too

    var my_app = ''; // define a variable which store string return by function
    /**
    * This function will return the appName
    * @return string
    */
    function appName()
    {
    my_app = 'OsinLab Application';
    return my_app;
    }
    
    console.log(appName());
  • Local Scope : A variable declared inside a function can be accessed within the function. So, scope of that variable is limited to function and this variable cannot be accessed by any other code outside the function. So, the variable is known as local variable and scope of that function is LocalScope. Local variable is created and destroyed each time when function is executed.
    /**
    * This function will return the appName
    * @return string
    */
    function appName()
    {
    var my_app = 'OsinLab Application';
    return my_app;
    }
    
    console.log(my_app); // this will give an error because the variable is local

Closures are functions that refer to variables that are used locally, but defined in an enclosing scope (Independent (free) variables).
In simple words, these functions ‘remember’ the environment in which they were created.

In JavaScript each function have access to globas scope. As well as each function have access to scope above them (Parent Scope). JavaScript allow to use nested functions. So, the nested function have access to the scope of function in which they defined.

function closureExample() {
var name = "OsinLab";
return function displayName() {
alert(name);
};
}

var myFunc = makeFunc();
myFunc();

 

Leave a Reply

Your email address will not be published. Required fields are marked *