views:

95

answers:

3

I use only jquery for writing javascript, one thing that confuses me is these two approaches of writing functions,

1st approach

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

2nd approach

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

Can anyone guide me what is the difference between the two and why one should use first approach or second approach ?

Thanks

A: 

The first one is a Function Expression

var calculateSum = function(a, b) { return a + b; }

alert(calculateSum(5, 5)); // alerts 10

The second one is plain function declaration.

rahul
+6  A: 

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

The main difference is that function statements are evaluated at parse time, they are available before its declaration at runtime.

See also:

CMS
Thanks CMS :) :)
Gaurav Sharma
+4  A: 
function myFunction() {}

...is called a "function declaration".

var myFunction = function() {};

...is called a "function expression".

They're very similar; however:

  • The function declaration can be declared after it is referenced, whereas the function expression must be declared before it is referenced:

    // OK
    myFunction();
    function myFunction() {}
    
    
    // Error
    myFunction();
    var myFunction = function() {};
    
  • Since a function expression is a statement, it should be followed by a semi-colon.

See Function constructor vs. function declaration vs. function expression at the Mozilla Developer Centre for more information.

Steve Harrison