5
What are the differences in declaring a function in these two ways:
Mode 1
var funcao = function() {
// ...
};
Mode 2
function funcao() {
// ...
}
What are the advantages and disadvantages of each?
5
What are the differences in declaring a function in these two ways:
Mode 1
var funcao = function() {
// ...
};
Mode 2
function funcao() {
// ...
}
What are the advantages and disadvantages of each?
6
In practical terms, the only difference is in relation to the code flow; if you try to call a function declared by Mode 1 (var funcao = function(...){...}
) before this line has been executed, you will receive an execution error. Mode 2, on the other hand, ensures that the function will be found even before the line of your statement has been effectively executed.
Just to clarify, consider the example below:
var msg;
msg = msgSpan("Olá"); // Modo 2: ok
msg = msgNegrito("Mundo"); // Modo 1: Uncaught ReferenceError: msgNegrito is not defined
function msgSpan(m){ return "<span>" + m + "</span>"; }
msgNegrito = function(m){ return "<span>" + m + "</span>"; }
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.