Skip navigation

Javascript is a expressive language. In continuation to the previous post, check the following code

//
var arr = ['x','y','z'];

for (var count = -1, l = arr.length, obj; obj = arr[++count], count < l;) {
  alert(obj);
}

// alerts x, y, z
//

Nothing wrong with conventional looping technique, but this is to explore JavaScript’s expressiveness!!!

Definition for closure : A closure is the local variables for a function – kept alive after the function has returned.

A nice example to explain closure.

//
// define a function which preserves data (count)
//
var CreateCounter = function(){
   var count, f;
   count = 0;
   f = function(){
      count = count+1;
      return count;
   }
   return f;
}

// create objects which remembers its own counter
var counter1 = CreateCounter();
var counter2 = CreateCounter();
alert(counter1());  // 1
alert(counter1());  // 2
alert(counter1());  // 3

alert(counter2());  // 1
alert(counter2());  // 2
alert(counter2());  // 3

alert(counter1());  // 4
alert(counter1());  // 5
alert(counter2());  // 4

Nice article about closure found at http://www.jibbering.com/faq/faq_notes/closures.html

In javascript function are first class objects. That means it can be used as values. Notice the example below

// function definition
function alertHi(name) {
   alert('hi! '+name);
}

// storing string
var name = 'rajakvk';

// storing number
var age = 26;

// storing function
var sayHi = alertHi;

// now sayHi is also function, you can call it like
sayHi();   // hi

Here is example to use function as parameter

// define a function to call a function twice
// here function f passed as parameter
var callTwice = function(f,x) {
   return f(f(x));
}
var addTen = function(x) {
   return x+10;
}
// here function addTen used as value 
var y = callTwice(addTen, 2);   // 22

Follow

Get every new post delivered to your Inbox.