Saturday, June 17, 2017

JavaScript – Different ways of Function Declaration

1. Function Declaration
This is normal way of declaration using “function” keyword followed by function name and list of parameters
Example:
function Add(a,b)
{
   return a+b;
}
Add(5,10) ; // output - 15
Add(2,3); // output – 5

2. Function Expression
  • It is determined by function keyword followed by list of parameters
  • It acts as anonymous function i.e. without function name
  • A function expression can be stored in a variable, after that the variable can be used as a function
Example: 
var x= function Add(a,b)
{
   return a+b;
}
x(5,10) ; // output : 15
x(2,3); // output : 5

3. Function Constructor
  • It is determined using “new” keyword followed by “function” keyword
Example:
var x = new function(“a”,”b”,”return a+b”);

x(5,10) ; // output : 15
x(2,3); // output : 5
4. Invoke Function as object method
  • It allows us to define function as object methods
Example:
var empObj = {
firstName: ” Christopher”
lastName: ” Nolan”
fullName: function() {
  return this.firstName + “ “ + this.lastName ;
  }
}
empObj.fullName(); // output : Christopher Nolan

5. Invoke Function with a Function Consturctor
  • If a function invocation is preceded with the new keyword, it is a constructor invocation
Example:
function emp(fname,lname)
    this.firstName = fname
    this.lastName = lname
    this.fullName: function() {
        return this.firstName + “ “ + this.lastName ;
    }
}
var empObj = new emp(“Christopher”,” Nolan”);
empObj.firstName; // output : Christopher

6. Self-Invoking Function
  • A self-invoking expression is invoked automatically, without being called.
  • b) Function expressions will execute automatically if the expression is followed by ()
Example: 
( function() {
     console.log(“Christopher”);
})();
// output : Christopher

Happy Coding :)

No comments:

Post a Comment