Why Does This Happen?
If you have a variable with the same name as a previously declared let
or const
variable within the same scope, then an error is thrown:
const x = 'foo';
// ...
// Uncaught SyntaxError: Identifier 'x' has already been declared
const x = 'bar';
The same happens when you declare a function expression with the same name (in the same scope):
const foo = function() {
console.log('foo');
}
// SyntaxError: Identifier 'foo' has already been declared
const foo = function() {
console.log('bar');
}
These issues happen because in a local scope (i.e. block or function scope) you cannot shadow another let
or const
variable (i.e. you cannot have a variable with the same name as a previously declared variable within the same scope).
This also means that this issue can happen within case
/default
in a switch
statement since they share the same scope as defined by their containing switch
statement:
const type = 2;
switch (type) {
case 1:
let foo = 'bar';
console.log(foo);
break;
case 2:
// SyntaxError: Identifier 'foo' has already been declared
let foo = 123;
console.log(foo);
break;
// ...
}
In all of the cases mentioned above, this happens regardless of which keyword (from var
, const
or let
) you use to declare the variable with the duplicate name (as you can see in the example below):
function printFoo() {
let foo = 'bar';
if (true) {
// SyntaxError: Identifier 'foo' has already been declared
var foo = 'qux';
}
// ...
return foo;
}
How to Fix the Issue?
To fix this error, you need to first identify the line of code that's causing the issue. Once you have identified the duplicate declaration, rename the variable or function to a unique name that has not been used before in the same scope.
For example:
const x = 'foo';
let x = 'bar'; // duplicate
// fix:
const x = 'foo';
let y = 'bar';
let x = 'foo';
var x = 'bar'; // duplicate
// fix:
let x = 'foo';
var y = 'bar';
Similarly, to fix this issue within case
/default
clauses in a switch
statement you can:
- Use unique variable names within the
switch
block, or; - Wrap each
case
/default
clause with curly braces ({}
) to give each its own block scope.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.