8

I use only jQuery for writing JavaScript code. One thing that confuses me is these two approaches of 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 one use the first approach or the second approach?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Gaurav Sharma
  • 2,830
  • 1
  • 36
  • 54
  • 3
    Unless `vote` has already been declared, `vote = function (action,feed...` should be `var vote = function (action,feed...`—it's bad practice to use implied globals. – Steve Harrison Jan 29 '10 at 07:21
  • 1
    possible duplicate of [JavaScript: var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname) – Tim Stone Apr 03 '12 at 23:28

4 Answers4

8

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:

Community
  • 1
  • 1
Christian C. Salvadó
  • 769,263
  • 179
  • 909
  • 832
6
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
  • 112,334
  • 15
  • 84
  • 71
0

The function declaration syntax cannot be used within a block statement.

Legal:

function a() {
    function b() {

    }
}

Illegal:

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

        }
    }
}

You can do this though:

function a() {
    var b;
    if (c) {
        b = function() {

        };
    }
}
ChaosPandion
  • 75,687
  • 16
  • 116
  • 154
0

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 a plain function declaration.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
rahul
  • 179,909
  • 49
  • 229
  • 260