0

I would like to make a simple counter with setInterval(), like this:

setInterval(() => {
  if(typeof i === 'undefined') {
    let i = 1;
  } else {
    i++;
  }
  console.log(i);
}, 1000);

What this does is it crashes saying how i is not defined and I would like to understand why?

Does it fail cause console.log(i) is not in the same scope as where let i = 1 is? So in JavaScript every { } block has its own scope? I know I could define i = 1 without if else, but would like to learn why does this example fail to work? Is it cause of scope?

Also, I would like this to work with defining a variable, only if it does not exist, something like isset() in PHP!

Sky Daddy
  • 11
  • 2
  • i is local variable within if context, error is correct, you need to declare it before if – Nonik Apr 14 '22 at 19:07
  • `let` and `const` are scoped inside if/else blocks, too. – Terry Apr 14 '22 at 19:08
  • In your line 2, you are asking for `typeof i`, but `i` never existed before that. The fix would be to add another line above the `if(` line: `let i;` – Bao Huynh Lam Apr 14 '22 at 19:08
  • To make the counter work, you need `i` to be global, declared outside the setInterval, or declared inside *without* var or let or const. – James Apr 14 '22 at 20:07

0 Answers0