mbeaudru / modern-js-cheatsheet

Cheatsheet for the JavaScript knowledge you will frequently encounter in modern projects.

Home Page:https://mbeaudru.github.io/modern-js-cheatsheet/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is the result of var declared variables demo code correct or should be clearer?

JasonBoy opened this issue · comments

commented

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:
screen shot 2017-09-26 at 1 06 44 pm

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);