javascriptfunction

Function calling method explanation


I have some doubts about function calling. Please look at these below 3 instances.

When i need to use function calling as function() { flip("hawaiian"); } When i need to use function calling as formValid[without braces]

Help me on this to understand better. I have still confusion on which situation i need to use these different methods.

hawaiiBtn.onclick = function() { flip("hawaiian"); };

formEl.onclick = formValid;

formEl.addEventListener("click", `formValid`);

Solution

  • Anonymous function with the inline click event

    hawaiiBtn.onclick = function() { flip("hawaiian"); };
    

    This is an anonymous function expression, that is assigned to the inline onclick event. Use this if you only need a single click handler on the element, and you don't already have an existing function, or don't want to reuse a function.

    Pass a function object to the inline click event

    formEl.onclick = formValid;
    

    Similar to the first method, but here you are passing a function object, or a named function, instead of creating a new function expression. Use this if you already have a function or want to reuse a function without duplicating code.

    element.addEventListener

    The difference between this and onclick is this can handle multiple click handlers for the same element and same event, whereas onclick can only take a single function. You can use anonymous functions or function objects.

    Example:

    element.addEventListener('click', function(){
        console.log("first fired");
    });
    element.addEventListener('click', function(){
        console.log("second fired");
    });
    

    Both of the above functions will execute when the click event is raised. However, doing that with the inline onclick will only execute the last function.

    element.onclick = function(){
        console.log("this will never fire because it gets overwritten");
    };
    element.onclick = function(){
        console.log("this will fire because its the last one, and will overwrite the previous");
    };