Unexpected global variable declaration should be avoided

  • UNEXPECTED_GLOBAL_DECL
  • Code Quality
  • Medium
  • No tags

This rule applies when global variable is unexpectedly declared.

Assigning a value to undeclared variable creates a new variable inside the global scope. Unexpectedly created global variables can cause memory leaks.

For example, unexpected global variables can be created in the following cases:

  1. Initialize a loop variable without declaration.
  2. Assign to an intermediate variable accessed only inside a loop without declaration.
  3. In the middle of variable declaration list, comma is missing or semicolon is inserted by mistake at the end of variable declaration.

Noncompliant Code Example

View with compliant examples side by side
// Example 1
var b = [1, 2, 3];
for (a = 0 /* UNEXPECTED_GLOBAL_DECL alarm */; a < b.length; a++) {}

// Example 2
function foo(x) {
    for (var i = 0; i < x.length; i++) {
        bar = getBar(x[i]); // UNEXPECTED_GLOBAL_DECL alarm
        doSomething(bar);
    }
}

// Example 3
var c = 1,
    d = 2
    e = 3, // UNEXPECTED_GLOBAL_DECL alarm
    f = 4; // UNEXPECTED_GLOBAL_DECL alarm

Compliant Code Example

View with noncompliant examples side by side
// Example 1
var b = [1, 2, 3];
for (var a = 0; a < b.length; a++) {}

// Example 2
function foo(x) {
    for (var i = 0; i < x.length; i++) {
        var bar = getBar(x[i]);
        doSomething(bar);
    }
}

// Example 3
var c = 1,
    d = 2,
    e = 3,
    f = 4;

Version

This rule was introduced in DeepScan 1.0.0-alpha.

Was this documentation helpful?