Fixing JavaScript error: Identifier has already been declared

Identifier has already been declared Error in JavaScript

In this article you’ll learn to fix “Identifier has already been declared” error in JavaScript by only declaring the variable once. Read on it now.

Why does this error happen?

The error occurs when either a const or let variable is redeclared in the same scope.

Breaking down keywords

A “scope” determines the accessibility of a variable, there are 3 types:

  • Global: Declared outside of a function or { } and can be accessed anywhere.
  • Function: Declared inside a function and can only be accessed in that function.
  • Block: Anything declared inside a { } (if, while, for, etc.) and can only be accessed outside of it if it has the var and not the const or let keyword.

The let keyword does not allow the variable to be redeclared and is block-scoped (i.e. cannot be used outside of { }).

The const keyword does not allow the variable to be redeclared or redefined and is block-scoped (i.e. cannot be used outside of { }).

The var keyword can be redeclared and be global-scoped or function-scoped (if declared in a function). However, please note that var is considered bad-practice by most programmers nowadays.

Example of Error:

let _var = 12;
let _var = 14;
console.log(_var);

Output:

The identifier "_var" has already been declared

How to fix the “identifier has already been declared” error in JavaScript?

To fix the problem, make sure the variable is only declared once. However, if the variable uses the const keyword, change the keyword to let or var if you wish to change its value.

Fix:

let _var = 12;
_var = 14;
console.log(_var);

Output:

14

Additionally, if you are using the var keyword, you can redefine it directly.

Fix:

var _var = 12;
var _var = 14; // Redefined
console.log(_var);

Output:

14

However, if you are dead set on using the const keyword, you can simply put the code in a different scope. Though this is heavily unadvised and you are better off just using the let keyword or just use a different but similar sounding variable.

Fix:

const _var = 12;

if (true) {
    const _var = 14;
    console.log(_var);
}

Be aware though that the programmer should not have variables with the same name in different scopes.

const _var = 12;
const __var = 15;
console.log(__var)

Output:

14

Summary

We hope you enjoy our article about the “identifier has already been declared” error in JavaScript. If you have any problems or any questions, please comment below. We will respond as possible. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *