1

I have two questions, can anyone explain that, please?
1- Why can I access btn outside the callback function and can't access x outside declareX?
2- How btn has two different values inside and outside the eventListerner?

console.log(btn); // logs the button itself
btn.addEventListener('click', () => {
  var btn = document.getElementById('btn').innerHTML;
  console.log(btn); // logs the innerHTML of the button
});

(function declareX() {
  var x = 0;
  console.log(x); // logs 0
})();
console.log(x); // error x is not defined
  • 3
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+dom+elements+with+id+become+global+variable) of [Do DOM tree elements with ids become global variables?](/q/3434278/4642212). – Sebastian Simon Jul 31 '21 at 11:37
  • 1
    See the answers to the [linked question](https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables). Basically, though: 1. Because it's an *automatic global* created by the browser. Elements with `id` attributes get put on the global object (`window` on browsers, loosely speaking) with the property name being the element's `id`. Properties of the global object whose names are valid identifiers are global variables. 2. Basically for the same reason. Outside the handler you're using the global, inside you're using your local variable instead. – T.J. Crowder Jul 31 '21 at 11:41
  • Welcome to SO! This stuff is not obvious, it's a good question and you asked it well (included enough information for us to answer, didn't include a lot of unnecessary stuff). :-) Don't let the "duplicate" thing bother you, it just means that although it's a good question, it's been asked and answered before, so rather than repeat things we point you at the previous answers. Happy coding! – T.J. Crowder Jul 31 '21 at 11:42
  • Thanks a lot, I understood the answer in the linked question – Asmaa Mahmoud Jul 31 '21 at 11:49

0 Answers0