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

139
Vistas
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 Respuestas
Responde la pregunta

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 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