How to use a global variable within a function?


Joined
Sep 12, 2022
Messages
30
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)
 
Ad

Advertisements

Joined
Jul 12, 2020
Messages
73
Reaction score
2
he's trying to tell you that it should be name="pp" in your form element instead of using id="pp".
 
Ad

Advertisements

Joined
Jan 30, 2023
Messages
71
Reaction score
2
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.
 
Ad

Advertisements


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

Top