Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!