Possible Duplicate:
The difference between the two functions? (“function x” vs “var x = function”)
JavaScript: var functionName = function() {} vs function functionName() {}
var test = function() {
var a = 20;
var b = 30;
return a + b;
};
function Add() {
var a = 20;
var b = 30;
return a + b;
}
What is the difference between these two functions? If I call add() or test() they both give me the same result. What exactly does the var
do?
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() {
};
}
}
For the language nerds among us you'll want to reference sections 12.1, 13.1, and 14 of the specification. You will find the following syntax descriptions.
12.1 Block
Syntax
Block :
{ StatementListopt }
StatementList :
Statement
StatementList Statement
13 Function Definition
Syntax
FunctionDeclaration :
function Identifier ( FormalParameterListopt ) { FunctionBody }
FunctionExpression :
function Identifieropt ( FormalParameterListopt ) { FunctionBody }
FormalParameterList :
Identifier
FormalParameterList , Identifier
FunctionBody :
SourceElements
14 Program
Syntax
Program :
SourceElementsopt
SourceElements :
SourceElement
SourceElements SourceElement
SourceElement :
Statement
FunctionDeclaration
They're different. If you call the function declared with a var before declaration, it will throw an error since it hasn't been declared yet.
test(); // Undefined
var test = function() {
...
};
This can be called however at any time and defined at run time.
test(); // OK
function test() {
...
};
The difference is that in the first case you have an anonymous function assigned to a name, and in the second, a function declaration. In most cases, this difference doesn't matter. Where it does matter is
variable hoisting causes the entire function declaration to be "moved" to the top of its containing function, so
foo(1, 2); var foo = function (a, b) { return a+b; }
is equivalent to
var foo;
foo(1, 2);
foo = function (a, b) {
return a+b;
}
(you can see why it would fail.)
You can invoke Add() before the its definition, but you can't invoke test() before its definition.
Also see var functionName = function() {} vs function functionName() {}.
The var
means you are assigning a variable to an anonymous function. If you were going to assign your function to a variable, you would do this:
var test = function Add() {
var a = 20;
var b = 30;
return a + b;
};
You have to name the function that you are using.
You don't have to assign a function to a variable, but if you would like to keep the data from the function then you should assign the function to a variable, so you would use the code above.
The first function you are assigning is an anonymous function to a variable test variable. Then variable test becomes the test() function.