JavaScript for WordPress Forums Vanilla JavaScript Function expressions / declarations on Events Reply To: Function expressions / declarations on Events

#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() {
};