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

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

    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.

    Zac Gordon

    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 ) { 
      console.log( 'Clicked );   
    }, false );

    jQuery .click and such things often encourage this approach.

    $( 'a' ).click( function() {
      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 ) { 
      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.