Question:
I see in some codes different ways to define a function, but I don't know the difference if it even exists. What is the difference between these functions?
Function 1
function teste(valor){
return (valor > 1) ? true : false;
}
Function 2
var teste = function(valor){
return (valor > 1) ? true : false;
}
Answer:
Function Declaration: function name()
A function declaration defines a function variable without the need for variable assignment. They are independent constructs , and cannot be nested in non-function blocks (see comment below). It would be like a "kin" of variable declarations. Just as variables need to be declared with var
, functions are declared with function
.
function bar() {
return 3;
}
bar() //3
bar //function
Function Expression: var name = function()
A function expression defines a function as part of a larger syntactic expression, typically a variable assignment. Functions defined with function expressions can be named or anonymous. Cannot start with function
, so parentheses are used in "auto invocation" in the example below:
//expressão anônima de função
var a = function() {
return 3;
}
//expressão nominada de função
var a = function bar() {
return 3;
}
//expressão "autoinvocada" de função
(function digaOi() {
alert("Oi!");
})();
Scope visibility example:
<script>
funcaoUm(); // Da erro, ainda nao foi definida
var funcaoUm = function() { }
</script>
<script>
var funcaoDois = function banana() {
banana(); // Nao da erro, está no escopo
}
banana(); // Da erro, está fora do escopo (exceto no IE)
</script>
<script>
funcaoTres(); // Nao da erro, é resolvida ao compilar
function funcaoTres() { }
</script>
"Functions cannot be declared in non-code blocks"
Let's look at this code:
if (true) {
function foo() {
return 'primeiro';
}
} else {
function foo() {
return 'segundo';
}
}
foo();
Some browsers will return "first", some "second"!
According to the specification, function declarations can even appear inside function blocks, but not inside if
, while
, for
and other building blocks.
In these cases, what should happen is a syntax error , but practically none of the implementations do this in practice, and what's worse, each one handles code like the example in a different way (with the exception of BESEB and DMDScripot, as per this one. source ).
Sources: Function Declarations vs. Function Expressions , SOen , kangax