Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
Why does a JavaScript event listener function need to be wrapped in function tags instead of just calling the function?

It has been awhile since I've worked in JavaScript and something just stumped me. I'm trying to call a function on an input change, but the function was running on page load only.

let textInput.document.getElementById('input');

textInput.addEventListener('input', myFunction());

Only runs on page load and doesn't seem to listen for the event at all. But

let textInput.document.getElementById('input');

textInput.addEventListener('input', function() {
    myFunction();
});

works as expected. I have looked around trying to figure out why this is happening, but the docs that I've reviewed seem to indicate that I should be able to just call the myFunction() within the listener, without wrapping it in another function. Can someone explain to me what is going on here please?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The function takes in the function as a variable, so in your case, just do myFunction instead of myFunction(). The way you are using it, the arguments provided to the listener are input and whatever your return value is from the function. using only myFunction, you provide the function as a value.

about 4 years ago · Juan Pablo Isaza Denunciar

0

When you have a reference to a function followed immediately by (), that will execute the function at the time that the statement is evaluated. This is true no matter the context.

someFn(someOtherFn());

is equivalent to

const innerResult = someOtherFn();
someFn(innerResult);

addEventListener works the same way - it just has a slight extra complication that it takes more arguments. That's why textInput.addEventListener('input', myFunction()); will run myFunction whenever the addEventListener line is executed.

the docs that I've reviewed seem to indicate that I should be able to just call the myFunction() within the listener, without wrapping it in another function

This is true - you can pass just the function itself, without calling it:

textInput.addEventListener('input', myFunction)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda