Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda