javascriptevent-listener

how add event listeners hold variables after be triggered


Im looking to understand better how listeners work in this situation, i have a JS file where i just put all indexs that match my \n position in a paragrph and display it after my loop is over. My question is, if i put my variables inside my function in add event listener, it is updated always i hit the button, but if i put at outside scope of addeventlistener it got repeated.

let Para = document.querySelector('p');

//Case when i put let n and inx inside add event listener
let btn = document.querySelector('button').addEventListener("click", function (){
    let n = 0;
    let inx = [];
    //find all /n ending and holding up their index
    for(X in Para.textContent){
        Para.textContent[X] == '\n' ? inx[n] = X : "";
        if( Para.textContent[X] == '\n') n++;
    }
    console.log('All "/n" are in the indexs : ' + inx);
    

});
/*DOM normal*/
body{
    background-color: black;
}
p{
    color: white;
}
<body>
    <p>Any paragrph
        with
        breaked lines
        to test all my \n
        catch
    </p>
   
    <button id="catch">CATCH</button>
</body>
</html>

it result in calling inx and n over and over again always i hit the btn, as it were a new array and a new n variable: enter image description here

but if i put my n and inx variable outside addevent scope, the display got messy and repeated many times the same output, inside my array. enter image description here

listeners just have a consistent way of dealing with our variable when it is inside their scope ?


Solution

  • The behavior you're observing relates to how variables are scoped in JavaScript, particularly when using event listeners and how JavaScript handles closures.

    Variables Inside vs. Outside Event Listener Variables Inside Event Listener: When you declare let n = 0; and let inx = []; inside the event listener function, these variables are initialized each time the event listener is triggered (e.g., each time the button is clicked). Since they are reinitialized with each click, the variables are fresh and start from their initial state.

    Result: The event listener works as expected, collecting the indices of \n and displaying them correctly every time the button is clicked. Variables Outside Event Listener: When you declare let n = 0; and let inx = []; outside the event listener function, these variables retain their values between each button click. Since inx keeps accumulating values from previous clicks, the indices from the previous click get appended, leading to duplicated entries in your inx array.

    Result: Each subsequent button click would append the new indices to the existing inx array, rather than starting fresh.