Question about 'let'

I was watching this video about the differences between const, let and var:

I wanted to ask about let and why at the 5min mark the result of cats is 15 in the console, as below.

I thought that let is block scoped, so shouldn’t console.log(cats) still give 2 since it’s in the global scope?


if(true) {
   cats = 15;

…in the block scope, so why does it change the global declaration of cats?

It doesn’t change the “global” status of the declaration. The global means anything beneath can access it. It just overwrites the value at a later point.

1 Like

Ok I kinda get it, thank you.

I guess I’m still just a little confused because I thought anything within curly braces is a separate scope so just still slightly confused…

Yes, let has a block scope, which means that if you put let before a variable name in a code block, this variable will only be accessible in this block.
As you can see, in line 13, there was no “let” in front of the variable name, so the variable name “cats” refers to the nearest declared variable with this name.

1 Like

I see, thanks so much. That makes it a lot clearer!!

1 Like

Hey there @chunzg :wave:,

Here’s a simple explanation about let:

let is a new feature as of ES6/EcmaScript2015. This is when a lot of features that will became a standard of JavaScript added, and let is one of them. Let is a variable declaration that will only be available in it’s block. It’s block scope. A block is { }, so if you declare anything inside that specific block, it can only be accessed inside the block. Other blocks inside this block can still access it, but anything outside of it can’t. Here’s an example:

function randomFunc() {
  let x = 5;
  if(x > 5) {
    console.log("I can still access x");

console.log("I cannot access x");
console.log(x); //Returns an error
1 Like

I’m glad I could help. Keep pushing, you’re awesome!

1 Like

I see, that makes sense about it being accessible inside the block but not outside it, it’s like there is a hierarchy. Thank you, think I get it now :slight_smile:

1 Like