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?
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?
Share Improve this question edited Apr 11, 2015 at 22:38 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Jan 29, 2010 at 7:03 Gaurav SharmaGaurav Sharma 2,8281 gold badge37 silver badges55 bronze badges 2-
3
Unless
vote
has already been declared,vote = function (action,feed...
should bevar vote = function (action,feed...
—it's bad practice to use implied globals. – Steve Harrison Commented Jan 29, 2010 at 7:21 - 1 possible duplicate of JavaScript: var functionName = function() {} vs function functionName() {} – Tim Stone Commented Apr 3, 2012 at 23:28
4 Answers
Reset to default 8The 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
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.
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() {
};
}
}
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.