Skip navigation

Tag Archives: function


While surfing through internet I came across one interesting JavaScript technic. Just observe the code snippet below

// self redefining function
var myFunction = function () {
    //set up code only to this once
    alert("set up, only called once");

    // set up code now complete.
    // redefine function so that set up code is not re-executed
    myFunction = function() {
        alert("no set up code");
    }
}
myFunction(); // outputs - Set up, only called once
myFunction(); // outputs - no set up code this time
myFunction(); // outputs - no set up code this time 
// 

In practical scenario we can use it intelligently. What do you say??? 🙂

Advertisements

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

You might be knowing how to call setTimeout javascript function. It is simple
setTimeout(myFunction, myTimeoutInMilliSeconds);

But if you want to pass a parameter with myFunction
setTimeout(myFunction(para), myTimeoutInMilliSeconds); // won't work

The javascript closure comes as a great rescue.
setTimeout(function(){myFunction(para)}, myTimeoutInMilliSeconds);

This is best example of using closure.