Difference between function and anonymity function in Javascript

Asked

Viewed 540 times

1

Hello I doubt what would be the difference between função and função anônima, follows the example of code of the two possibilities .

FUNCTION 1

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

FUNCTION 2

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

    https://answall.com/questions/165984/difference%C3%A7a-between-a-syntax-to-declare-a-fun%C3%A7%C3%A3o

1 answer

1


Well the only syntactic difference is that the anonymous function does not have a stated name. But there is a difference in usage, since an anonymous function has no name, it cannot 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 be executed, Functions are isolated code snippets that are called as often as needed

examples of usability:

ANONYMOUS FUNCTION:

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

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

  • 1

    Examples should be copied to the answer. The link may no longer exist in the future.

  • Sure. I’ll move the examples now

  • 1

    When you create a anonymous function with a variable const myVar = function() { ... }, it can be used several times in a code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.