Doubt when calling function in Javascript - use of parentheses

Asked

Viewed 207 times

3

I am studying a little Javascript, and I came across a situation that I did not understand very well. The author creates a function and when he will call it by the onclick method he does not put the relatives of the function...

        function mostrarAlerta(){
            alert("Hello World!");
        }

        var botao = document.querySelector("button");
        botao.onclick = mostrarAlerta;

that is to say, botao.onclick = mostrarAlerta; in that mostrarAlerta shouldn’t parentheses come? Like botao.onclick = mostrarAlerta()?

1 answer

3


Not. botao.onclick = mostrarAlerta assigns the function mostrarAlerta to the property onclick. The function itself is the value being passed.

If on the other hand you use botao.onclick = mostrarAlerta(), you would be invoking the function, and assigning the return of mostrarAlerta to the property onclick. That is to say, onclick would receive undefined (value returned by a function when you do not explicitly declare the return).

So you want to assign the function mostrarAlerta or undefined à onclick? This is why parentheses are not used in this example.

  • Got it! Thanks a lot!

Browser other questions tagged

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