How to remove compiler warning message

I am receiving this error warning message, how is it fixed in the code?

Functions declared within loops referencing an outer scoped variable may lead to confusing semantics

I have googled this error message and somewhat understand why it appears but I don’t really understand how I can fix it in my particular case.

What would need to be changed or adjusted in the code to remove the warning?

https://jsfiddle.net/6hLo87xv/

function createResetHandler(player) {
  const resetVideos = document.querySelectorAll('.exit');
  for (let i = 0; i < resetVideos.length; i ++) {
    resetVideos[i].addEventListener('click', function resetVideoHandler() {
      player.destroy();
    });
  }
}

Originally using forEach:

  function createResetHandler(player) {
    const resetVideos = document.querySelectorAll('.exit');
    resetVideos.forEach(function resetVideoHandler(video) {
      video.addEventListener('click', function resetVideoHandler() {
        player.destroy();
      });
    });
  }

Hi @javascriptcoding5678

The warning seems to disappear if you assign player.destroy to a const variable within the loop. I suggest you read through the responses to this stackoverflow question and fully understand what the warning is about because I am also not very sure whether assigning the method to a variable within the loop is a solution or just a workaround.

for (let i = 0; i < resetVideos.length; i++) {
    const destroy = player.destroy;
    resetVideos[i].addEventListener('click', function resetVideoHandler() {
       destroy();
 });
1 Like

That is giving me a "Script error." in the code. https://jsfiddle.net/obmeudav/

Maybe, that is not how it would be fixed in the code.

  function createResetHandler(player) {
    const resetVideos = document.querySelectorAll('.exit');
    for (let i = 0; i < resetVideos.length; i++) {
      const destroy = player.destroy;
      resetVideos[i].addEventListener('click', function resetVideoHandler() {
        destroy();
      });
    }
  }

Well unfortunately I don’t see the same error on my end.

Did you click on the play svg buttons?

Did you click the Exit button?

Try again: https://jsfiddle.net/obmeudav/

It’s neither a solution or a workaround.

That code gives me an error message.