As Member 15627495 hinted at in the comments, clicking the button submits the form, which will cause the page to reload and lose any changes made by your script.
You either need to change the button to
type="button"
, or prevent the form from being submitted.
For example:
<form>
<label for="userName">
What's your name?
<input type="text" id="userName" />
</label>
<button type="button" class="btn">Submit</button>
</form>
<p class="demo"></p>
const userName = document.querySelector("#userName");
const demo = document.querySelector(".demo");
const btn = document.querySelector(".btn");
btn.addEventListener("click", e => {
e.preventDefault();
demo.textContent = `Hello, ${userName.value}`;
console.log(userName.value);
});
Demo[
^]