Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two? [duplicate]

I saw the following JavaScript functions works exactly same, Then what is the difference between them other than syntax. The function are:

var functionName=function(){
    //some code here
}; 

function functionName(){
    //some code here
} 

I call them in the same way as:

functionName();

Please dont' tell me there syntax is different, Other than that is there any difference like

1)speed of execution
2)Memory utilization etc.

Thanks in advance!

like image 377
sandip Avatar asked Mar 05 '13 04:03

sandip


1 Answers

This has been answered many times in StackOverflow. It is just the way of naming. So taking up some points from the answers, I would say:

  1. Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there.

  2. Advantages & Disadvantages:

    There are few advantages to naming functions:

    • names for meta analysis. functionInstance.name will show you the name.
    • Far more importantly, the name will be printed in stack traces.
    • names also help write self documenting or literate code.

    There is a single disadvantage to named functions expressions

    • IE has memory leaks for NFE
  3. Another main difference

    The difference is that functionTwo is defined at parse-time for a script block, whereas functionOne is defined at run-time. For example:

    <script>
      // Error
      functionOne();
    
      var functionOne = function() {
      }
    </script>
    
    <script>
      // No error
      functionTwo();
    
      function functionTwo() {
      }
    </script>
    

References

  1. var functionName = function() {} vs function functionName() {}
  2. Are named functions or anonymous functions preferred in JavaScript?
  3. Named function expressions demystified
  4. Function Declarations vs. Function Expressions.
  5. var functionName = function() {} vs function functionName() {}
like image 104
Praveen Kumar Purushothaman Avatar answered Oct 16 '22 01:10

Praveen Kumar Purushothaman