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

141
Visualizações
javascript function returns undefined instead of array values?
let btns = document.querySelectorAll("button");

function choosenOrder(chices1) {
  let btnsPair = [chices1[0], chices1[1]];
  btnsPair.forEach((choice) => {
    choice.addEventListener("click", (c1) => {
      let mychoice = c1.target.textContent;
      return mychoice;
    })
  })
}
console.log(choosenOrder(btns));

//return undefined

I will be simple and direct...

I want to return the text value of the button i press using the listener function inside addEventListener. However this is not working as expected, and what ever i try it either returns undefined or not work at all, is it even possible to return a value from an event listener?

If it is not, what kinda of alternatives do I have?

Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The return statement is inside the event handler, and cannot be taken into account by the wrapping function (when the handler is executed - asynchronously, the wrapping function call has already ended and returned). An alternative could be to use Promises. In the outer function, return the Promise, and inside the event listener, resolve that Promise with the value:

let btns = document.querySelectorAll("button");

function choosenOrder(chices1) {
  return new Promise(resolve => {
    let btnsPair = [chices1[0], chices1[1]];
    btnsPair.forEach((choice) => {
      choice.addEventListener("click", (c1) => {
        let mychoice = c1.target.textContent;
        resolve(mychoice);
      });
    });
  });
}

choosenOrder(btns).then(console.log);
<button>Choice A</button>
<button>Choice B</button>

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