Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two functions/approaches?

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?

like image 359
Gaurav Sharma Avatar asked Jan 29 '10 07:01

Gaurav Sharma


People also ask

What is the difference between the two functions?

The difference of two functions can be found by subtracting the two individual functions from each other. Follow these steps to effectively find the difference between two functions: Subtract the second function from the first, remembering to distribute the negative sign to each term.

What is the difference between the function?

Definition of Relation and Function in Maths Functions- The relation that defines the set of inputs to the set of outputs is called the functions. In function, each input in set X has exactly one output in set Y. Note: All functions are relations but all relations are not functions.


2 Answers

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:

  • Named function expressions demystified (article)
  • Explain JavaScript’s encapsulated anonymous function syntax
like image 55
Christian C. Salvadó Avatar answered Sep 20 '22 03:09

Christian C. Salvadó


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.

like image 24
Steve Harrison Avatar answered Sep 21 '22 03:09

Steve Harrison