user8758206
user8758206

Reputation: 2191

Cannot find variable in a simple function inside a for of loop (safari)

I'm trying to discover why Safari returns a console error whereas other browsers like Chrome have no problem. There is a simple function inside a for of loop as follows:

const links = document.querySelectorAll('ul > li > a');

console.log(links); // successful

for (const link of links) {
    console.log(link); // successful
  
  function logLink() {
    console.log(link);
  }
  
  logLink();
}
<ul id='test'>
  <li>
    <a class='one' href='#'>test 1</a>
  </li>
  <li>
    <a class='two' href='#'>test 2</a>
  </li>
  <li>
    <a class='three' href='#'>test 3</a>
  </li>
</ul>

Codepen: https://codepen.io/ns91/pen/oNNEKpP

Open the above codeine URL in safari and open your javascript console. As you can see, in Safari, the function logLink(); doesn't seem to log the link variable, although it works in Chrome.

The error I'm getting is: ReferenceError: Can't find variable: link

Does anyone know why this is happening, and how to fix it?

Thanks for any help here.

Upvotes: 2

Views: 707

Answers (1)

Quentin
Quentin

Reputation: 944075

Function declarations are scoped to the function they are declared inside and hoisted (so it is outside the for loop's block) but const declarations are scoped to the containing block.

link only exists inside the block, logLink lives outside it, so logLink doesn't have access to the link constant.

Use a function expression and a const so the function is scoped to the for loop's block like the link constant.

const links = document.querySelectorAll('ul > li > a');
for (const link of links) {
  const logLink = function logLink() {
    console.log(link);
  }
  logLink();
}
<ul id='test'>
  <li>
    <a class='one' href='#'>test 1</a>
  </li>
  <li>
    <a class='two' href='#'>test 2</a>
  </li>
  <li>
    <a class='three' href='#'>test 3</a>
  </li>
</ul>

Upvotes: 2

Related Questions