Redeclaration refers to the act of declaring a variable or function with the same name more than once within the same scope. In JavaScript,
variable and function redeclarations are allowed but can lead to unexpected behavior and potential bugs in your code.
- Function declarations can be redeclared using the
function
keyword. In this case, the latest function declaration will overwrite
the previous one.
- Variables declared using
var
can be redeclared within the same scope without any errors. The subsequent redeclaration will not
affect the previous variable.
- Variable declarations with
var
in the same scope as a function named the same override the function’s value.
This rule checks that a declaration doesn’t use a name already in use, whether variables, functions, or parameters. Such redeclarations are
misleading and could have been made by mistake, the developer not realizing that the new assignment overwrites the symbol value.
var a = 'foo';
function a() {} // Noncompliant: Overriden by the variable 'a'
console.log(a); // prints "foo"
function myFunc(arg) {
var arg = "event"; // Noncompliant: Shadows the parameter 'arg'
}
fun(); // prints "bar"
function fun() {
console.log("foo");
}
fun(); // prints "bar"
function fun() { // Noncompliant: Replaces the previous declaration of 'fun'
console.log("bar");
}
fun(); // prints "bar"
To avoid issues with variable and function redeclarations, you should use unique names as much as possible and declare variables with
let
and const
only.
let a = 'foo';
function otherName() {}
console.log(a);
function myFunc(arg) {
const newName = "event";
}
fun(); // prints "foo"
function fun() {
print("foo");
}
fun(); // prints "foo"
function printBar() {
print("bar");
}
printBar(); // prints "bar"