So I had an x is not defined error in my code which confused me a little bit because x was already defined couple lines before. I had to spend some time tweaking my code, deleting and adding lines until I managed to understand why it was happening. After I removed every unnecessary information, now the code looks like this:
let foo = 2;
console.log(foo);
if (foo === 2){
console.log(foo);
let foo = 1;
}
It throws foo is not defined at line 5. An error pops out when I'm trying to console.log(foo) ! If I remove line 6 let foo = 1; the code works fine. I mean an error happens before I declare foo for a second time. So the first question is:
- How is it possible that line 6 (which hasn't been executed yet) makes line 5 end up with an error?
The second thing I can't understand is why does it say foo is not defined instead of foo has been already declared.
If I replace the second let with var an error will appear at line 6 and it will say foo has been already declared so it looks fine. But having let being set as the second identifier always throws an incorrect error.
- Why does it throw an incorrect error?
After testing different scenarios I noticed that the outcome depends on which identifiers I use:
identifiers | result
----------------------------------------------
var var | the code works well
var let | not defined error
let var | has been already declared error
let let | not defined error
So the 3rd question is:
- Why is everyone against of using
varwhen in this scenario double usingvaris the only way the code works flawless? Is it an exception?