Why even without creating a variable referencing the elements in HTML the code still works?

Asked

Viewed 21 times

3

let demo = document.querySelector("#demo");
let button = document.querySelector("#button");

button.onclick = () => {
    demo.innerHTML = "Novo texto!";
}
<p id="demo"></p>
<button id="button">click</button>

Above the code is very simple to illustrate what I’m talking about, I created two variables demo and button referring to the elements in HTML, when clicked on the button changes the text inside the paragraph so far so good, but if I remove the variables demo and button the code keeps working without any problem:

button.onclick = () => {
    demo.innerHTML = "Novo texto!";
}
<p id="demo"></p>
<button id="button">click</button>

Or even more, no error is returned as, for example:

Uncaught ReferenceError: button is not defined at

Wasn’t to return an error similar to the above since the variable was not defined or doesn’t exist? because it happens in the code Javascript?

No answers

Browser other questions tagged

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