Variable "forgets" that has been assigned to the other and function returns Undefined

Asked

Viewed 46 times

0

function pegarBotaoClicado (botoes) {
    let botaoClicado

    botoes.forEach(botao => {
        botao.addEventListener("click", function (e) {
             botaoClicado = botao
        })
    })

    return botaoClicado
}

In this function I created the intention is to grab the button clicked inside an array of buttons. The problem is that in the line botaoClicado = botao, was for the variable botaoClicado take the value of the button. This happens, I used the browser debug and there I can see that actually the variable takes the value.

The problem is that when returning this variable, the function returns undefined. You seem to have forgotten that you’ve been assigned a variable. I think the problem is scope-related, but I have no idea and I’ve done a lot of research.

  • You can’t try to take a variable from inside the callback.

  • I can’t do assignment inside the callback?

  • 1

    You can do assignments. What you can’t do is trying to assign a variable from inside the callback out of it. Can even do as you did. No exception will be thrown, but it is certain that wrong behaviors will occur.

  • Which do you think would be a solution? I’m practically a beginner yet

  • That question, although it is Promise, can give you an idea of why this is wrong: https://answall.com/questions/379212/como-attributed-resultado-de-umapromise-a-uma-vari%C3%a1vel/379215#379215

  • 1

    Most likely you don’t need to "grab" the clicked button. Just put your logic inside the callback of addEventListener, which will only run for the buttons that are clicked.

  • 1

    I always talk, but it’s no use, it’s fashionable. Most of the uses of forEach() are completely unnecessary and the for normal works best. This function has a lot of bad and harmful side effect, hard to understand even for those who are experienced, apart from the limitation of things that it is easy to do with for. The people like to Clever code. The sad thing is, some people teach it to make you look smarter, and whoever’s learning it thinks it’s better. It might even be in very specific cases. And I like the functional style.

  • if I change to be solves the problem?

  • The problem is that .forEach() is asynchronous and you end up returning before the loop ends and surely nothing will help your "event" ... you could clarify what kind of matrix is "buttons" (an element Arary or a nodeList) and what you hope to get with the return, so maybe then actually get a help

Show 4 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.