Global and local variable conflict in Event function in JavaScript

I know this has been asked a lot of times before, but all the reference questions dealt with the scoping issue. I can’t wrap my head around this. I even debugged it and in the Call Stack, it shows the value of the count as String but the innerTExt doesn’t changes to String. But when I change the name of the count variable inside the function, it works fine. Since, local variable and global variables have different Call Stack, it should be perfectly okay.Can anybody explain how is it working on Call Stack and behind the scenes?

<div><h1>Hello World !</h1></div>
    <button class="event-button">Click me</button>
    <div class="counter">count:0</div>
    <script>
      const button = document.querySelector(".event-button");
      const count = document.querySelector(".counter");
      button.addEventListener("click", function () {
        const count = "String";
        count.innerText = count;
      });
    </script>

>Solution :

This has absolutely nothing to do with the call stack.

You have shadowed count inside the function.

This means you have two variables named count in different scopes.

When you access count inside the function, you access the closest one, which is the one you defined inside the function.

You do not have access to the one in the wider scope.

<button class="event-button">Click me</button>
<div class="counter">count:0</div>
<script>
    const button = document.querySelector(".event-button");
    const count = document.querySelector(".counter"); // <= The value assigned to the count variable in the outer scope is set to the return value of the querySelector method: an HTMLElement object
    button.addEventListener("click", function () {
        // The value assigned to the count variable in the inner
        // scope (different from the 'count' found in the outer 
        // scope is set to a String value)
        const count = "String";
        // The count variable (a String) does not have a property `innerText`
        count.innerText = count;

        // What you want to do instead is replace the two lines above with this one:
        count.innerText = "String"; // <= Just keep this one and count will reflect he variable declared in the outer scope
    });
</script>

Leave a Reply