Question on scope and variables. How do I work around this? Codepen included

A Pen by Trenton (

so, if you look in my function on line 66 in my JavaScript called checkForCorrectAnswer I am initializing a variable called questionInputField. That variable is coming from line 52 in my JS.

now the problem is that I can’t use that variable anywhere else, and I also can’t initialize it outside of that function because that HTML is not created until the quiz is rendered.

in the next function below checkForWrongAnswer I need to use that variable because I need the value of it, but it undefined in that function.

I also need that variable for other parts of my code because I want to focus the input field upon completing a question and I can’t do that because it’s not global

is there any possible way to make a variable global from within a function? I’m trying to figure out how to solve this.

Why do you need a separate functions checkForCorrectAnswer and checkForWrongAnswer? Why not have a function named checkAnswer that does what needs to be done for the right answer and does something else for the wrong answer?

1 Like

I needed this…haha

I’ve become so obsessed with trying to have functions do only one thing that this flew over my head. I’ve been trying to focus on writing readable code and keep functions very simple.

I’ve had a problem with going back to old projects and have no idea what is going on.

So, although my problem was fixed, I still am stuck at a wall because I need questionInputField to be able to be used outside of that function.

I want to make it focused upon clicking the start quiz button and also focused when the user submits a question answer. It’s rather annoying if someone has to keep clicking the input field after submitting a question. I know how to do this with .focus() however outside of that function questionInputField does not exist. Is there any way around this or did I just hit a wall in my project?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.