Thursday, September 6, 2012

JavaScript Tips and Tricks -5

1) Here are different ways in which you can define a JavaScript function -
a)
    function func(x){
    alert(x);}
    func('myName');
b)
    var func = function(x){
    alert(x);}
    func('myName');
c)
    var func = new Function("x" ,"alert(x);");
    func('myName');
d)
    window.func= function(x){ alert(x); };
    func('myName');

2) Sometimes in JavaScript the order of function definition does not matter. Here is the example -
if(typeof (func) == "undefined")
    alert('func is undefined');
else
    alert('func is not undefined');
function func(){ return true; }
The above alerts - func is not undefined.
But this statement is not true for any kind of assignment. Which includes the function assignment as well.
Which means if we defined function in any one of these format,it wont be possible to use them before assigning it. -
 window.func= function(x){ alert(x); };
 var func = new Function("x" ,"alert(x);");
 var func = function(x){alert(x);}
Which means following code will give output as "func is undefined" -
if(typeof (func) == "undefined")
    alert('func is undefined');
else
    alert('func is not undefined');   
var func = function(x){alert(x);}

3) We can always define functions below return statement. For example -
 function TestFunc(){
  alert(func());
  return func();
  function func(){ return true; }
}
TestFunc();
Above function will return as true.

4) Its always possible to have recursive calls in Java Script functions. Here is example-
function factorial(num){
    if(num == 0 || num == 1)
        return 1;
    else return num*factorial(num - 1);
}
alert(factorial(4));

5) How to implement Cache in JavaScript -
 var getSquare = function(num) {   
    if(getSquare.cache[num] == null)
        getSquare.cache[num] = num * num;
       
    return getSquare.cache[num];
}
getSquare.cache = {};

alert(getSquare(3));
alert(getSquare.cache[3]);

No comments:

Post a Comment