0

I just can't understand, before last if - log outputs int value, after if - same log shows error:

"Cannot access 'nextImgId' before initialization" whats up with that? The caraible is declaired before it is used, so it can be because of temporal dead zone.

let nextImgId = img.getAttribute('data-next-id');
if (nextImgId !== null) {
  nextImgId = parseInt(nextImgId);
  log(nextImgId);
  if (true) {
    log(nextImgId);
  }
}

function log(...args) {
  console.log(...args)
};
<img id=img src=//placekitten.com/50/50 data-next-id="123" />

I have tried refreshing the page expecting for reality to make sense, but it didn't happen :(

I know that this code is working and I can't just upload my project, where it doesn't work. The question could be what might cause a variable to disappear... Not what ir wrong with this code.

SOLVED: My mistake was to not include the rest of the code inside the if, where the problem was, that the variable was redeclared and that made the scope of that variable change.

darkė
  • 47
  • 6
  • 1
    I've converted your code to a live demo and made a bucket of assumptions about the bits it depends on but which you didn't include. I agree that the duplicate isn't good, but I can't reproduce the problem so it should remain closed (the reason is just wrong). Please read [ask] and provide a real [mcve]. – Quentin Nov 27 '22 at 19:58
  • 1
    "I know that this code is working" — Then it's not helpful code to include in the question. – Quentin Nov 27 '22 at 23:25
  • 1
    "The question could be what might cause a variable to disappear" — See the duplicate. – Quentin Nov 27 '22 at 23:25
  • 2
    "*The variable is declared before it is used*" - apparently it isn't. The TDZ is the only explanation for the error message you got (see the duplicate). If you actually need to solve the problem with your code, you'll need to post a [mcve] that lets us reproduce the problem. – Bergi Nov 27 '22 at 23:30

0 Answers0