Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference b/w Function Declaration & Function Expression

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 308
    Comment on it

    Hello readers, Today in my blog I would like to discuss about the difference b/w Function Expression and Function Declaration.

     

    The first question that arises in the readers mind would what basically these both terms mean,  so here is the answer to it.

     

    What is function?

    A function is like a variable which can be defined anywhere in the code.

     

    In other words, function can be defined as a small named snippets of code that can be invoked using their name within the code.

     

    It can take any type of parameter.

     

    How to create Functions ?

    There are many ways to create functions such as -:

    • Function declaration :

    example :-

    function printMsg (msg) {console.log(msg);}
    • Function expression :

    example :-

    var printMsg = function ( ){console.log(msg);}
    • With Function constructor :

    example :-

    var printMsg = new
    
    Function(msg,console.log (msg););


     

    What is a Function Declarations ?

    It is defined as a named function variable without need of variable assignment.

     

    It uses a function operator to create a function object.

     

    Below is the example showing function declaration within a code.

    printMsg(Hello);
    
    function printMsg(msg){
    
    console.log(Message: +msg);

    }

     

    The function declaration are loaded first in their scope and allows using a function before it is defined.

    What is Function Expression ?

    These are created using functions literals and they are loaded where they are defined in the code.

     

    The function Expression can be named or anonymous.

     

    Below is an example of anonymous function expression :-

    var a = function( ){
    
    return 3;
    
    }

    Below is an example of named function Expression :-

    var a = function bar( ) {
    
    return 3;
    
    }

    Here is an example of Function Expression :-

    var printMsg = function (msg){
    
    console.log(Message: + msg);
    
    }
    
    printMsg(Hello);

    Conclusion :-

    In the simple words we can say that when a JavaScript parser sees a function in the main code, then it assumes its as a function declaration while when a function is written as a part of statement then ,it is termed as function expression.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: