skip to Main Content

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 ?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Rather than a long speech, maybe your corrected code will be easier to understand?

    const Para = document.querySelector('pre');
    
    document.querySelector('#catch-1').addEventListener("click", btnClickEvent_fct );
    document.querySelector('#catch-2').addEventListener("click", btnClickEvent_fct );
    
    
    function btnClickEvent_fct( evt )
      {
      let inx = [];
     
      for( let X in Para.textContent )
        {
        if( Para.textContent[X] === 'n')   inx.push( X );
        }
    
      console.clear();
      console.log(`from ${evt.target.id} ->`);
      console.log(`All "\n" are in the indexs :  ${inx}`);
      }
    pre {
     background-color: lightgrey;
    }
    <pre contenteditable>Any paragrph
    with
    breaked lines
    to test all my
    catch
    </pre>
    
    <button id="catch-1">CATCH 1</button>
    <button id="catch-2">CATCH 2</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search