While making several test projects for my small library of code I have come across many tutorials that go about making functions in many different ways.
For example:
Function Declarations
FunctionDeclaration : function Identifier ( FormalParameterList opt ){ FunctionBody }
Function Expressions
FunctionExpression : function Identifier opt ( FormalParameterList opt ){ FunctionBody }
Anonymous Self-Executing Functions
(function(msg){ alert(msg); })('SO'); // alerts "SO"
Anonymous Self-Executing Functions that I have seen in source code that I suspect may be incorrect but I want to make sure
(function(msg){ alert(msg); }('SO')); // alerts "SO", but the passed parameter appears inside the parenthesis that wrap the function, not after like I think is correct.
With all this said, I want to clear the air about a few questions I had regarding each of the types of functions.
A function declaration:
function display(){
//this function is evaluated at parse time,
can be called any time
}
Is it true that a function declaration (that is evaluated at parse time and does not require parenthesis after the brackets) can be overwritten by function expressions as this question seems to indicate and this source code seems to back up?:
var display = function(){
//this function will be called as opposed to the
//display() declaration (above) any time
//display() is used after this variable assignment
};
A function expression:
var display = function nameOptional(){
};
Is the semi-colon after the bracket in function expressions that has been assigned to a variable necessary? And also, does that mean that this:
function name(){
//...
};
is different than this:?
function name(){
//...
}//no semi-colon
Is the first name()
a function expression, and the second name()
a function declaration? Or is the first name()
a function expression and the second name()
a function expression with an optional left-out semi-colon. Because I have read that in function expressions, the semi-colon is only recommended.
What confuses me is that in a function declaration you must have an identifier, and a body. In an expression, the identifier is optional, but you must have a body. So if you have
function identifier(){
//...body...
}
is this a declaration, or an expression since the semi-colon is not required on expressions or declarations. On expressions it is only recommended for optimum results in the case of variable assigning.
An Anonymous Self-Executing Function:
I understand how these work, but I have seen two ways of writing this, one I am almost certain is wrong. I just would like to clear this up:
(function(msg){
alert(msg);
})("SO");
and
(function(msg){
alert(msg);
}("SO"));
I have read that the reason an anonymous function executes is because it is wrapped in ()
and if you want any parameters to be passed to it, they must be added after those ()
and before a semi-colon tying the whole thing off, if this is true...the second anonymous function is written incorrectly...is this true?