I wrote the following code in code editor to produce error:
const a = 1;
console.log(a);
const a = 1; // Uncaught SyntaxError: Identifier 'a' has already been declared
I did the same thing directly into console --
const a = 1; //undefined
const a = 1; //undefined
const a = 2; // undefined
a // 2
Why here error was not caught?
Assuming you're using Chrome, this is by design. const
redeclarations was intentionally implemented in Chrome Devtools 92 as a means to make it easier for developers to test code within the Chrome console (my emphasis):
The Console now supports redeclaration of const statement, in addition to the existing let and class redeclarations. The inability to redeclare was a common annoyance for web developers who use the Console to experiment with new JavaScript code.
As the blog post points out, it enables you to redeclare const
and other bindings you wouldn't usually be able to redeclare. This means something like:
> const a = 1;
> const a = 2;
is allowed as the two lines of code are executing in separate REPL scripts (indicated by the >
), whereas performing:
> const a = 1;
const a = 2;
x Uncaught SyntaxError: Identifier 'a' has already been declared
is not allowed as this is redeclaring const
within the one REPL script (multiple lines of code can be entered into the one command line using SHIFT + ENTER).
This change is only for the Chrome devtools console, and not for regular page scripts, which will throw a SyntaxError as expected if you try and redeclare const
.