Javascript function declaration [duplicate]

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?

    
asked by anonymous 03.09.2014 / 22:43

1 answer

6

In practical terms, the only difference is in relation to the flow of the code; if you attempt to call a function declared by Mode 1 ( var funcao = function(...){...} ) before this line has been executed, you will receive a runtime error. Mode 2, on the other hand, guarantees that the function will be found even before the line of its declaration has actually been 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>"; }
    
03.09.2014 / 22:52