7

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!

sandip
  • 3,279
  • 5
  • 31
  • 54

2 Answers2

1

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() {}
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0
  1. 1st one is Named Function Expressions, which should return some value to the caller.
  2. 2nd one is just a function, it's upto you whether you return value or not
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83