When to use parentheses with javascript function [duplicate]

showText returns the function showText.

showText() runs the function showText and returns the result.

When you attach a function to an event handler like .onclick, it is expecting a function.

You can call a function and return the result to an event like this: document.getElementById("mybutton").onclick = showText(); provided the function itself returns a function:

function showText() {
    return function () { 
        alert('hello world'); 
    }
}

Leave a Comment