JavaScript for WordPress Forums Vanilla JavaScript Function expressions / declarations on Events

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #27776
    bruno
    Participant

    Hi, Zac!

    Glad to say Hi again!.

    I have another question regarding Events:

    Why sometimes do you use function expressions on events and in other examples you use function declarations?

    tx, Bruno.

    #27792
    Zac Gordon
    Keymaster

    Hey Bruno!

    Good question 🙂

    My goal in this section is to show you both. Later one you will see function references used more than expressions.

    However, you will often see expressions used because they are “easier” to write right where you add the event listener.

    
    el.addEventListener( 'click', function( event ) { 
      event.preventDefault();
      console.log( 'Clicked );   
    }, false );
    

    jQuery .click and such things often encourage this approach.

    
    $( 'a' ).click( function() {
      event.preventDefault();
      console.log( 'Clicked' );
    }); 
    

    The downside to using function expressions with an event handler is that you can’t easily remove that event handler because it has no name to reference it. You would not necessarily need to always do this, but it is one con.

    Another larger issue is that it is more common to separate your function declarations and assignments from the event listener. This allows for cleaner and better organized code.

    
    el.addEventListener( 'click', clickFunc, false);
    
    // Function separated
    function clickFunc( event ) { 
      event.preventDefault();
      console.log( 'Clicked );   
    }
    
    // Ability to remove the function because its named
    el.removeEventListener( 'click', clickFunc, false);
    

    Was that what you meant?

    Or did you mean this:

    
    var myFunc = function() {
    };
    

    versus this?

    
    function myFunc() {
    };
    
Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.