What is the difference between these two functions / approaches?

I use only jQuery to write JavaScript code. One thing that bothers me is two approaches to writing functions,

First approach

vote = function (action,feedbackId,responseDiv) { alert('hi'); return feedbackId; } 

Second approach

 function vote(action, feedbackId,responseDiv) { alert('hi'); return feedbackId; } 

What is the difference between the two and why should you use the first approach or the second approach?

+7
javascript function
source share
4 answers

The first is the function expression assigned to the vote variable, the second is the function declaration.

The main difference is that function operators are evaluated at the time of parsing; they are available before it is declared at run time.

See also:

+8
source share
 function myFunction() {} 

... is called a "function declaration".

 var myFunction = function() {}; 

... is called a "functional expression".

They are very similar; But:

  • A function declaration can be declared after a reference, while a function expression must be declared before its reference:

     // OK myFunction(); function myFunction() {} // Error myFunction(); var myFunction = function() {}; 
  • Since a function expression is an instruction, it must be followed by a semicolon.

See Function Designer vs. Function Declaration and Function Expression in the Mozilla Developer Center for more information.

+6
source share

The first is an expression of a function,

 var calculateSum = function(a, b) { return a + b; } alert(calculateSum(5, 5)); // Alerts 10 

The second is a simple function declaration.

0
source share

Function declaration syntax cannot be used in a block statement.

Allowed:

 function a() { function b() { } } 

Illegal:

 function a() { if (c) { function b() { } } } 

You can do this though:

 function a() { var b; if (c) { b = function() { }; } } 
0
source share

All Articles