Functions or variables should not be redeclared
- DUPLICATE_DECL
- Code Quality
- Medium, Low
- No tags
This rule applies when a function or a variable is redeclared in local context.
In JavaScript, it is possible to redefine the function and only the last one is used. This causes confusion as to where the function is actually defined.
Since functions and variables are hoisted in JavaScript, redeclared variables combined with hoisting and function-scoped var
statement cause confusion as to where the variable is defined.
function foo() {
var code = 1;
if (true) {
var code = 2;
}
console.log(code); // code has a value of 2 because 'var' is not block-scoped
}
Note:
- This rule applies only for the variable whose name is length of 3 characters or above. It is because short variable name, e.g.
i
, is frequently used as loop counters. - Not applied at test case code because duplicate declarations are usually harmless at tests and tend to occur more. Currently, BDD, TDD and QUnit style test cases are recognized.
Noncompliant Code Example
View with compliant examples side by sidefunction a() { return 1; } // DUPLICATE_DECL alarm. This function declaration is ignored.
function a(b) { return b; }
var foo;
var foo; // DUPLICATE_DECL alarm
Compliant Code Example
View with noncompliant examples side by side// Choose the function which you intend to apply. And delete others.
function a(b) { return b; }
// Delete duplicated one
var foo;
Version
This rule was introduced in DeepScan 1.0.0-alpha.