You can declare again, that’s not the problem of the code you posted.
let a = 2;
{
console.log(a); //aqui aparece 2
let a = 3; // aqui ja da erro, não aceita
}
You wrote aqui aparece 2
, but that’s not what’s happening. The problem is in itself console.log(a)
, not in the let a = 3
.
What’s going on here is called hoisting
. Javascript reserves all variables declared in the local scope when starting the scope, but despite this let a
already be booked, you cannot access it until after the line it has been declared.
That is, the console.log(a)
is trying to access the let a
local, but the let a
location is not yet valid, and this is the source of the error.
Also note that this is the behavior only of variables declared as let
or const
. Variables declared as var
can be accessed before your declaration without releasing exceptions, however its value will be undefined
.
Great answer, well noted that there does not appear 2.
– RXSD