How to use a global variable within a function?

Joined
Sep 12, 2022
Messages
39
Reaction score
0
If I move the variable inside of the function, the code executes but once I move it outside of the function it doesn't. Why?
HTML:
<input id="pp" type=text></input>
<button id="button">Start</button>
JavaScript:
 const pp = document.querySelector("input").value;
ks = () => {
  console.log(pp);
}
document.querySelector("#button").addEventListener('click', ks)
 
Joined
Jul 12, 2020
Messages
89
Reaction score
9
he's trying to tell you that it should be name="pp" in your form element instead of using id="pp".
 
Joined
Jan 30, 2023
Messages
107
Reaction score
13
When you declare the variable pp outside of the function, it only captures the value of the input element at the time it is declared. It does not update when the value of the input element changes, so when you click the button and run the ks function, it will always log the same initial value of pp.

If you move the declaration of pp inside the function, it will capture the current value of the input element each time the function is executed, so the function will log the updated value of the input element each time the button is clicked.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,829
Messages
2,569,737
Members
45,521
Latest member
maryb

Latest Threads

Top