Is the result of var declared variables demo code correct or should be clearer?
JasonBoy opened this issue · comments
In the var demo:
function myFunction() {
var myVar = "Nick";
console.log(myVar); // "Nick" - myVar is accessible inside the function
}
console.log(myVar); // Undefined, myVar is not accessible outside the function.
Is the last line should throw an exception? instead of undefined
since it's not accessible:
You are right. It's the same problem in the let section. The last console.log throw an error.
function myFunction() {
let myVar = "Nick";
if (true) {
let myVar = "John";
console.log(myVar); // "John"
// actually, myVar being block scoped, we just created a new variable myVar.
// this variable is not accessible outside this block and totally independent
// from the first myVar created !
}
console.log(myVar); // "Nick", see how the instructions in the if block DID NOT affect this value
}
console.log(myVar);