Today, Will discuss How many type of functions is available in javascript.
So There are 3 type of functions is available in javascript
- Named Function
- Anonymous Function
- Immediately Invoked function expression.
A function which has a name at the time of definition called Named function
Syntax:
function function_Name(param1, param2){
function body
}
function_Name();
Such function which don't have name are called Anonymous Function These functions are declared dynamically at runtime using the function operator instead of the function declaration. The function operator is more flexible than a function declaration and to invoked these function we assigned it to a variable.
Syntax:
var fun = function(param) {
do something here (Body of the function)
}
fun(param);
Let's understand with an example.
<script type ="text/javascript">
var anonymousFun = function(param1, param2) {
alert(param1 + " Good morning " + param2);
}
anonymousFun("Hello", "anonymous function");
</script>
Add the above code to a web page an run the application then output would be :
Hello Good morning anonymous function
Invoked function expression are those function which runs as soon as the browser encounters it. The main benefit of function is that it runs immediately where it’s located in the code and produces a direct output. That means it is unaffected by code which appears further down in the script which can be useful.
<script type ="text/javascript">
var msg = (function(){
var name= "Dal Chand";
return name;
})();
</script>
Outpou: Dal Chand