Thursday, June 13, 2013

JavaScript Closure.

What is a Closure :

Closure is a reference to a function together with the referencing environment.

Two important things to note in the above definition is that closure comprises of two things as follow
  1. A reference to a function.
  2. Binding function's referencing environment (in our case local variables inside the function's scope).
Let us see an example to grasp these two points better.

function HelloWorld(){
    var msg = "Hello World";
    function PrintHelloWorld(){
        alert(msg);
    };   
    return PrintHelloWorld;
};


var referenceToPrintHelloWorld = HelloWorld();
referenceToPrintHelloWorld();


Output of this program : [Hello World]

In the above code snippet, function HelloWorld() returns a reference to PrintHelloWorld(). PrintHelloWorld() closes over the local variable "msg" of HelloWorld(), which is in its execution environment. Here execution environment is the scope in which this function in declared and that is scope of HelloWorld function. Hence this satisfies definition of closure.

Notice though "msg" is defined locally inside HelloWorld's scope but still when we call referenceToPrintHelloWorld() from scope outside of HelloWorld() it alerts the value "msg". This is the magic of closures which closes over any local variable in its scope.

A Use Case : Classic last value problem

Preparation code

<html>
<body>
  <button id="button1" >Button 1</button>
  <button id="button2" >Button 2</button>
  <button id="button3" >Button 3</button>
  <button id="button4" >Button 4</button>
  <button id="button5" >Button 5</button>

</body>
<script>

  for (var i = 1; i <= 5; i++) {
    document.getElementById('button' + i ).onclick = function() {
      alert('You clicked on BUTTON with unique number : ' + i );
    };
  }
</script>
</html>


This is a simple code in which onclick event is attached to the buttons using a loop. When user clicks a button its unique number is supposed to be alerted, e.g When user clicks on the first button it is supposed to alerts "You clicked on BUTTON with unique number : 1". Where this unique number is supposed to be assigned during the loop execution.

Go ahead, run this program and see the output.

Output of this program irrespective of which button you press is always : [You clicked on BUTTON with unique number : 6].
No matter which button you click all the button have the same unique number "6" attached to them.

The root of this confusion is that all the onclick event refer to the same variable i , and at the end of the loop the value of i is 6. So whenever you click on any button it refers to the same variable i which has a value of 6 now. This is exactly the "last value" problem.

So how do you solve this problem ???

You might have guessed it by now and its closures ( though there are other way too). Since closures binds the context (in our case a unique number for every button).

So what we do to solve this problem we assign closures to onclick event rather that simple functions.

Here is the solution.

for (var i = 1; i <= 5; i++) {
  document.getElementById('button' + i).onclick = (function(){
    var uid = i;
    return function(){
        alert('You clicked BUTTON with unique number : ' + uid);
    };
  })();
};


In this solution the value of i is stored in the execution environment which is binded to the function that is returned by the self executing anonymous function. 
 
This is not the best elegant solution. The variable uid is used in this example to just highlight that value of i is stored in the local variable uid which is in the execution environment.

Elegant way of doing this would be passing the value of i as argument to self executing functions scope.

for (var i = 1; i <= 5; i++) {
  document.getElementById('button' + i).onclick = (function(uid){   
    return function(){
        alert('You clicked BUTTON with unique number : ' + uid);
    };
  })(i);
};


P.S.


Closure is a fun thing in JavaScript and can be applied to problems where context of execution has to remembered. Go on and take a dive into closures.    

Wednesday, June 12, 2013

Scoping and Hoisting in Javascript

Scoping


What is the output of following JavaScript code.

  var x = 1;
  {
   var x = 2;
   console.log("Inside: " + x);
  }
  console.log("Outside: " + x);


If your answer is 2,1 then you must read on.

In JavaScript function is the only thing that creates a new scope

Lets see an example to understand what this means.

var x = 1;
function y() {  

     var x = 10;
     console.log("Before Exiting y's scope the value of x is : " + x);
}
console.log("Outside y
's scope the value of x is : " + x);

y();

Output of this program is

    Outside y's scope the value of x is : 1
    Before Exiting y's scope the value of x is : 10

The reason is function y() creates its own local scope and any variable in functions scope is local to its scope. Here var x = 10 declaration inside scope of  function y() overshadows var x = 1 declaration in global scope.

Lets modify the above example a little bit and see what happens.

  • Program 2:

var x = 1;
function y() { 

     console.log("On Entering y's scope the value of x is : " + x);
     console.log("Before Exiting y's scope the value of x is : " + x);
}
console.log("Outside y
's scope the value of x is : " + x);

y();


  • Program 2 (modified):

var x = 1;
function y() { 

     console.log("On Entering y's scope the value of x is : " + x);
     var x = 10;

     console.log("Before Exiting y's scope the value of x is : " + x);
}
console.log("Outside y
's scope the value of x is : " + x);

y();

If you expect the result as 1,1,1 and 1,10,1 then you must watch closely.
  • Output of Program 1 is : 1,1,1 
  • Output of Program 2 is : undefined,10,1
Some of you may find it very amusing that why the value of x on entering y's scope in Program 2 is undefined ?


The answer to this subtle question is scoping and variable declaration hoisting.

 

Hoisting

Variable Declaration Hoisting


Program 2 is internally interpreted as below, declaration of variable x inside will be hoisted to the top of its scope (in our case scope of function y() ). Only declaration is hoisted not the assignment.

On entering function y() scope the program try to access the value of x but by this time only x is declared not assigned, hence JavaScript returns undefined. This is a subtle but important understanding. 

  • Program 2: Variable Declaration hoisting 

var x = 1;
function y() {

     var x;
     console.log("On Entering y's scope the value of x is : " + x);
     x = 10;

     console.log("Before Exiting y's scope the value of x is : " + x);
}
console.log("Outside y
's scope the value of x is : " + x);

y();

Function Declaration Hoisting


Like variables functions are also hoisted. Hoisted in a sense browser first loads the function declaration before anything else is loaded.

Lets see an example of function declaration hoisting.

  • Program 3: Function Declaration hoisting

bar();

function bar() {
    console.log('bar called.');
};
 
 


Output of this program is :  [bar is called]
The reason is as already said function declaration is loaded upfront by the browser before it loads anything else.

Functional Expression hoisting


Lets see another slightly different example.
 
  • Program 4: Functional Expression hoisting

foo();

var foo = function () {
    console.log('foo called.');
};
 

Output of this program is : [TypeError : foo is not a function].

The slight difference between Program 3 and Program 4 is use of  functional expression in the later .

Remember only declaration is hoisted not assignment. Hence internally Program 4 is interpreted as.

 

  • Interpreted Program 4: Functional Expression hoisting

var foo;
foo();
foo = function () {
    console.log('foo called.');
};


Here foo is only declared not assigned any type at the point where call is made and this call is assumed of type function which is an error, hence TypeError .

Conclusion

  1. Function is the only thing that creates a new scope in JavaScript.
  2. Only variable declaration is hoisted to the top of its scope, assignment is not hoisted.
  3. Function declaration (not functional expression) is loaded first by the browser before it loads anything else. 

 

Tuesday, June 11, 2013

JNI - Java Native Interface

Java Native Interface


JNI is a standard programming interface used to solve following problems.
  1. Write Java native methods.
  2. Embedding Java Virtual Machine(JVM) into native application.

Java native Methods:

Java native methods allow programmers to write methods in some other programming languages, such as C , C++ etc. Use case for native methods are as following.
  1. Use certain system functionality that can't be done using pure java.
  2. Get performance mileage by implementing performance sensitive methods in native over pure java.
Follow the link for sample code. Native method Step by Step 

Embedding JVM into native application:

There are certain cases when we require to call existing Java methods in our native code. This is achieved by embedding JVM into our native application.

Follow the link for sample code. Embed JVM in native C code