When I declare a variable using the let keyword that is already declared using the let keyword in the same scope, then it throws a SyntaxError exception. Consider this example:<
Let and Const Declarations will throw an error if you redeclare them in the same scope. However, they follow different rules in that their declarations aren't hoisted and their scope is limited to the first set of containing curly braces.
Reference: https://www.quora.com/What-does-happen-if-we-re-declare-a-variable-in-JavaScript
let
gives you the privilege to declare variables that are limited in scope to the block, statement of expression unlike var, but you can not re-declare the same variables in the same scope using let
. If you want to change the value of the variable in the same scope just remove the declaration part:
let a = 0;
a = 1;
function foo() {
let b = 2;
b = 3;
if(true) {
let c = 4;
c = 5;
}
}
foo();
In your example a SyntaxError
is thrown. So what is happening and why this error is thrown? Simply you are not conforming the rules for the syntax (because you try to redeclare let
variable which is wrong syntax according to the Javascript engine) and the Javascript engine (both in the Browser and in NodeJS) encounters this wrong syntax when parsing the code and throws a SyntaxError
.