Solve - Identifier has already been declared Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Marc Bombenon

Solve - Identifier has already been declared Error #

The "Identifier has already been declared error" occurs when a variable with the same name has been declared multiple times in the same scope using the let or const keywords. To solve the error make sure to only declare variables a single time in a scope.

javascript identifier has already been declared

Here are some examples of when the error occurs.

index.js
const num = 10; // ⛔️ Identifier 'num' has already been declared const num = 10; function sum() {} // ⛔️ Identifier 'sum' has already been declared const sum = 15; // ⛔️ Identifier 'i' has already been declared for (let i = 0, i < iterable.length, i++) { // 👆️ should use semicolons not commas }

We declared the num variable twice and got the error because we're not allowed to re-declare a variable that was declared using the const or let keyword.

index.js
// ⛔️ Identifier 'x' has already been declared let x = 10; let x = 15;

If you want to reassign the variable, you can use the let keyword to declare it and omit the keyword when reassigning it.

index.js
let x = 10; x = 15; console.log(x); // 👉️ 15

If you have difficulty finding out where the error is thrown, check out your browser's console or your terminal if you're using Node.js.

javascript identifier has already been declared

This screenshot above shows that the error occurred in the index.js file on line 12.

You can paste your code into an online Syntax Validator. The validator should be able to tell you on which line the error occurs.

You can also hover over the squiggly red line to get additional information.

When declaring a variable of the same name in different scopes use the const or let keywords, don't use var.

index.js
const x = 15; if (true) { const x = 100; console.log(x); // 👉️ 100 }
It's generally a bad practice to declare a variable with the same name in different scopes because it shadows the value of the variable in the outer scope and makes your code a bit harder to read.

To solve the "Identifier has already been declared error", make sure to only declare a variable once in a scope. Declaring a variable of the same name twice in the same scope throws the error when using the const and let keywords.

Use the search field on my Home Page to filter through my more than 1,000 articles.