Variables should be declared before they are assigned

  • ASSIGN_BEFORE_DECL
  • Code Quality
  • Low
  • No tags

This rule applies when local variables are assigned before they are declared.

In JavaScript, variables are hoisted and it is possible to use a variable before its declaration. But it is not recommended because it causes confusion as to where the variable is actually declared.

Therefore to avoid confusion, variables should be declared in the beginning of the function body before they are used.

Note: Not applied for the variables in inner functions because it is likely to be a programmer's intent.

Noncompliant Code Example

View with compliant examples side by side
function foo() {
    bar = 4; // ASSIGN_BEFORE_DECL alarm
    var bar;
    console.log(bar);
}
foo();

Compliant Code Example

View with noncompliant examples side by side
function foo() {
    var bar = 4;
    console.log(bar);
}
foo();

Version

This rule was introduced in DeepScan 1.0.0-alpha.

Was this documentation helpful?