Exact meaning of Function literal in JavaScript
The biggest difference is how/when it is parsed and used. Take your exemple,
myFunction = function() {
alert("hello world");
}
You can only run myFunction()
after the code got to there, since you declare a variable with an anonymous function.
If you use the other way,
function myFunction(){
alert("hello world");
}
This function is declared at compile time and can be used anytime in the scope.
Please refer to this question also.
Add-on:
A function literal in JavaScript is a synonym for a function expression.
Parallel to function expressions, function literals can have an optional identifier (name).
So if we say function expressions / function literals, it includes function expressions / function literals without an identifier (also called anonymous functions), but also function expressions / function literals with an identifier. Even if in a lot of books function expression / function literal is used as a synonym for function expression / function literal without an identifier (anonymous functions).
Function Literal
Function objects are created with function literals:
// Create a variable called add and store a function // in it that adds two numbers.
> var add = function (a, b) {
> return a + b; };
A function literal has four parts.
The first part is the reserved word function.
The optional second part is the function's name. The function can use its name to call itself recursively. The name can also be used by debuggers and development tools to identify the function. If a function is not given a name, as shown in the previous example, it is said to be anonymous.
The third part is the set of parameters of the function, wrapped in parentheses. Within the parentheses is a set of zero or more parameter names, separated by commas. These names will be defined as variables in the function. Unlike ordinary variables, instead of being initialized to undefined, they will be initialized to the arguments supplied when the function is invoked.
The fourth part is a set of statements wrapped in curly braces. These statements are the body of the function. They are executed when the function is invoked.
A function literal can appear anywhere that an expression can appear...
source: JavaScript: The Good Parts - Douglas Crockford
That means:
myFunction = function () {
alert("hello world");
};
is a function expression / function literal, but also:
myFunction = function myFunction() {
alert("hello world");
};
is a function expression / function literal.