3 ms·
Won't work: if(checkForSomething()) { let foo = 2; } else { let foo = 3; } console.log(foo); // won't work But: if(checkForS
by dheera 5y ago
Won't work:
if(checkForSomething()) {
let foo = 2;
} else {
let foo = 3;
}
console.log(foo); // won't work
But:
if(checkForSomething()) {
var foo = 2;
} else {
var foo = 3;
}
console.log(foo); // will work
That said, I religiously avoid "var" and just declare the variable beforehand with "let" because there are too many other gotchas with var. Less debugging headaches. And use "const" religiously as well, like C++ people do.
- speedgoose 5y agoconst in C++ is very different than const in JavaScript though. I guess you are well aware of that but I feel like being pedantic. This is allowed in JavaScript: const foo = {bar: 1}; foo.bar = 2;
- int_19h 5y agoThat's exactly what I meant by "any "var" could be replaced with "let" at a different scope": let foo; if (checkForSomething()) { foo = 2; } else { foo = 3; }