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:
Illegal:
You can do this though:
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