0
    document.getElementById("somethings").addEventListener("click", function() {
        // code code code
    });

    // ============= or like this =============

    document.getElementById("somethings").addEventListener("click", fun);
    
    function fun(){
        // code code code
    }

As a newbie i ask, is one of those more "correct" then the other?

Rebsh
  • 1
  • 1
  • The second one is wrong `.addEventListener("click", fun())` should be `.addEventListener("click", fun)`. See [addEventListener calls the function without me even asking it to](https://stackoverflow.com/q/16310423). Other than that, there isn't anything inherently "more" or "less" right between the two. – VLAZ Aug 14 '21 at 16:52
  • It's a callback. –  Aug 14 '21 at 16:53
  • You are passing the result of a function call and not a function, so your code won't work. – leodavinci1 Aug 14 '21 at 16:58

1 Answers1

0

It comes down to preference, but declaring functions to have your logic scoped separately from the event is a good practice, also I have noticed that you are calling the function instead of passing the reference of a function:

Your code:

function fun(){
  // code code code
}

document.getElementById("somethings").addEventListener("click", fun());
    

Do this:

function fun(){
  // code code code
}

document.getElementById("somethings").addEventListener("click", fun);
    
leodavinci1
  • 109
  • 8