Introduction to javascript functions,variables,scopes and closures

With Javascript language it is very easy to get started and at the same time it is really hard to get some of the concepts because of its very nature which made it easy to understand. So let's start getting few basic things straight.

Variables and their scope

To declare variable, use below syntax


    var name="xyz";
    var date=new Date()
  

"var" keyword sets the variable scope to local (atleast to the current module scope).

So what is global scope and local scope?

Consider below code


    var name1="xyz";

    function helloWorld(){
       var name2="abcd"
        alert("hello world")
    }

  

Go ahead, copy and paste this code on to google chrome's console (Press F12 in chrome to open developer tools, find console tab there) and press enter, this will define variable "name1" and function named "helloWorld".

Go ahead and type "name1" in console and hit enter, this will show you the value of name1 i.e. "xyz" in console. Lets try to get name2, follow same steps and you get "undefined" response on the console, this is because of scoping as we have defined name1 outside the "helloWord" function and it is not enclosed within any of the namespace, so name1 is registered as global variable. And in browser global variable would be window so you should be able to access "name1" variable as just "name1" or you can also access it with window.name1.



   name1
   window.name1
  

Since "name2" variable is defined inside "helloWorld" function, this variable scope is limited to "helloWorld" function. To verify that lets tweak "helloWorld" function a little bit as below:


    function helloWorld(){
       var name2="abcd"
        console.log("hello world "+name2);
    }
  

Copy and paste the above code in console (this will overwrite the old definition of "helloWorld" function, so you dont have to worry about that) and execute the same by calling function as below in your console.



  helloWorld();
  

Output should be as follows:

helloWorld

So variable "name2" can be accessed only from within "helloWorld" function, hence "name2" variable scope is limited to "helloWorld" function.

Though using global scoped variables makes things easier in the beginning, it is a bad idea to use global scoped variables as this could cause a conflict at global scope and cause your code to break or even bad, it might lead to erroneous outputs. For example, assume, above function (helloWorld) is a re-usable code and I distribute this code, if some developer is using this code in his project and developer includes other useful libraries in his project which also has variable named "name1" at global scope, this could lead to overwriting of one of the variable with other one and would lead to erroneous results. Hence it is always a good idea to enclose variables within a local scope.

Functions

Functions are set of lines of code which performs perticular task and can be re-used.
Functions reduces writing of code again and again, and helps in modularizing the source code.

Examples: Above code block "helloWorld" is a function which performs writing hello world on to the console. Below "multiPly" is a reusable function, performing multiplication of 2 passed variables



  function multiply(a,b){
      return a*b;
  };
  

Functions are first class objects in javascript i.e. you can also create an instance of a function and it acts as an object.

For example : Lets define a function called "Animal" which has properties (or variables), type (e.g., mammals), name (e.g., dogs), sound (e.g., bhou bhou).


function Animal(type,name,sound) {
    this.type = type;
    this.name = name;
    this.sound = sound,
    this.makeSound = function() {
        console.log(this.sound)
    }
}
  

As javascript considers functions as first class objects you should be able to create instances of Animal object. And you should be able to access their properties (like type, sound) and method as shown below.


    var dog=new Animal("mammals","dog","bhou bhou"); //Creates dog instance
    var cat=new Animal("mammals","cat","Meow Meow");//creates cat instance
    dog.makeSound();// prints "bhou bhou" sound
    cat.makeSound();// prints "bhou bhou" sound
  

Output should be as below

You would notice few "undefined" in the console output don't worry about them, it shows undefined as we are not returning anything from the function.

So functions can also act as objects, hence we can send them as a parameter to other functions (this concept is used in callbacks, to know more about callback see this blog)

Closures

Mozilla developer network defines closures as - "Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created".

Lets look into this definition with example.


  function greetings(name){
        function helloWorld(){

            console.log("hello world "+name);
        }

        return helloWorld;
    }

    var helloWorld1=greetings("Vijay"); //closure methods
    var helloWorld2=greetings("XYZ"); //closure
    helloWorld1();
    helloWorld2()
  

So in above code, we are creating a "helloWorld" function inside "greetings" function. "helloWorld" function is accessing local variable(i,e., name ) of "greetings" function. Hence making it a Closure.

Power of closure can be seen in next few lines of code, line "greetings("Vijay");" is returning "helloWorld" function and variable "name" has value "Vijay" and next line returns "helloWorld" function and variable "name" has value "XYZ". "helloWorld1()" is a new function created by invoking "greetings" function and "greetings" function is acting as a function factory creating helloWorld functions as in need. Executing "helloWorld1()" would output the log message as "hello world Vijay" and executing "helloWorld2()" would output log message as "hello world XYZ". This means function "helloWorld1" is remembering the local variables at the time of creating it.

So "helloWorld1()" and "helloWorld2()" are special kind of functions which share the same function body definition but remember the environment (like variable) in which it is created (like "name" variable, value being "Vijay" for helloWorld1 and XYZ for helloWorld2 ). This gives similar and alternative approach to Object oriented approach. Also provides powerful scoping mechanism to avoid global variable clashes.

Practically closure are boon to event driven programming as they remember the environment in which they are created, one of the simple example I can give for closure is "onClick" event of a button. The callback gets called on click of a button and has the access to its parent environment at the time of its creation.

In conclusion, javascript is loosely coupled, intuitive and amazing language, which is introducing new paradigm to do things differently.