CodeNewbie Community

Discussion on: What is the scope of variables in JavaScript?

Collapse
jacobmgevans profile image
Jacob M-G Evans

Ok so a little on this. I am going to ignore var for this it's special and for another time.
So let's talk about block scope. When I am writing something in a file there is a global level outside all functions, once I enter a function I am inside the scope of that function, however it doesn't end there, say I enter a statement block like if (something) { statement block scope } now comes the interesting part...

const unicorn = "unicorn";
console.log(unicorn); //unicorn

if (true) {
  // Scoping allows for variable shadowing
  const unicorn = "differentUnicorn";
  console.log(unicorn); // differentUnicorn

  const rainbows = "RAINBOW";
  console.log(rainbows); // "RAINBOW"
}

function hellowWorld() {
  const helloWorld = "MyName"; // 'helloWorld' is declared but its value is never read.
}

console.log(helloWorld); // helloWorld is not defined

console.log(rainbows); // rainbows is not defined
Enter fullscreen mode Exit fullscreen mode