The let statement can be used inside the code block. Why is this true?

Hi all. I’ve already know how to use var statement, like this:

var aNumber = 5;

And I’ve learned how to use let statement also.

However, I have a question.

The let statement can be used inside the code block {}. Why is this true?

var aNumber = 5;
if (aNumber === 5) {
    let aNumber = 10;
    console.log(aNumber);
}
// Why is this true?

If you guys know, then give me feedback.

Thanks!
Pummarin :grinning:

because let is block scoped, that variable declared with let exists only inside the code block, if you put the console log outside the if statement, the aNumber variable will have value of 5

1 Like

I already know that the let statement creates the variable locally but is block scoped, like this:

var aNumber = 5;
// I am defining the aNumber variable, with its value of 5.
if (aNumber === 5) { 
    // this test is true.
    let aNumber = 10; // aNumber is already set to 10.
    console.log(aNumber); // 10
}

Thanks for the answer!
Pumnarin :blush:

why already? you set it in this line