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 variable as above can cause memory leaks.

For example, unexpected global variable can be created as the following cases:

  1. Initialize an undeclared loop variable
  2. 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
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
var c = 1,
    d = 2,
    e = 3,
    f = 4;

Version

This rule was introduced in DeepScan 1.0.0-alpha.