Difference between function and anonymous function in JavaScript [duplicate]

1

I'm wondering what the difference between função and função anônima is, follow the code example of the two possibilities.

  

FUNCTION 1

titulo.addEventListener("click"), function(){
  console.log("Olá");
}
  

FUNCTION 2

titulo.addEventListener("click", mostraMensagem);
function mostraMensagem(){
  console.log("Olá");
}
    
asked by anonymous 26.02.2018 / 19:29

1 answer

1

Well the only syntactic difference is that the anonymous function does not have a declared name. But there is a difference in use, since an anonymous function has no name, it can not be called multiple times in a code, it is used more in callbacks of other functions

Anonymous functions are like, scripts to be executed that are written WHERE they will run, Already the functions are snippets of isolated codes that are called as many times as necessary

Usability examples:

ANONYMOUS FUNCTION:

setTimeout(function() {
   console.log('código executado na função anônima')
},300);

In this case the anonymous function is not a declaration of a function that will be used later, but a code to be executed!

    
26.02.2018 / 19:41