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:
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.
listeners just have a consistent way of dealing with our variable when it is inside their scope ?