Author By Teacher(Vijaya) Chapter-7
Function Expressions
There are two ways to define a function: by
1.function declaration
2. function expression.
Function Declaration:
function functionName(arg0, arg1, arg2) {
//function body
}
> name property on functions exposing the assigned name.
Ex: alert(functionName.name); //”functionName”
> key characteristics of function declarations is function declaration hoisting, whereby function declarations are read before the code executes.
Ex:
sayHi(); function sayHi(){ alert(“Hi!”); }
This example doesn’t throw an error because the function declaration is read fi rst before the code begins to execute.
Function Expression:
var functionName = function(arg0, arg1, arg2){
//function body
};
The created function is considered to be an anonymous function, because it has no identifier after the function keyword. (Anonymous functions are also sometimes called lambda functions.) This means the name property is the empty string.
Ex: sayHi(); //error – function doesn’t exist yet var sayHi = function(){ alert(“Hi!”); };
Function Declaration | Function Expression | //never do this! if(condition){ function sayHi(){ alert(“Hi!”); } } else { function sayHi(){ alert(“Yo!”); } } | //this is okay var sayHi; if(condition){ sayHi = function(){ alert(“Hi!”); }; } else { sayHi = function(){ alert(“Yo!”); }; } |
Recursion: A recursive function typically is formed when a function calls itself by name .
Ex: function factorial(num){ if (num <= 1){ return 1;
} else { return num * factorial(num-1);
}
}
Although this works initially, it’s possible to prevent it from functioning by running the following code immediately after it:
var anotherFactorial = factorial; factorial = null; alert(anotherFactorial(4)); //error!
because it will try to execute factorial(),