Home > Blockchain >  Object scope on methods
Object scope on methods

Time:07-06

let's say I code:

let btn = document.querySelector("button");
btn.addEventListener("click",() => console.log(btn.textContent));

Can somebody explain why the btn variable, that is storing a reference to a DOM node, can be accessed inside of the callback function passed to the addEventListener method? I thought that it was out of scope but I saw that the code runs without problems.

I'm new to JS so please don't be rude ahaha.

CodePudding user response:

Any code that appears in a scope (inner) (be it defined by a function, block, etc) has access to any variable in the scope (outer) where the inner scope was created unless that variable is shadowed.

CodePudding user response:

Because your variable is created in the global scope. There more information.

  • Related