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!