Loop should not be used when only a single iteration is needed

  • USELESS_LOOP
  • Code Quality
  • Low
  • No tags

This rule applies when an unconditional break, return or throw is used inside a loop body.

When a control flow statement like break, return, or throw statement is used in a loop without a condition, the enclosing loop will not repeat but execute only once.

For code readability and maintainability, it is recommended to use simpler if statement instead of the loop that executes only once. Also, it might be a mistake that the programmer forgets to check a condition before executing the control flow statement.

Note: Not applied for for-in or for-of loop because this pattern is often used for checking an empty array or object.

Noncompliant Code Example

View with compliant examples side by side
// Example 1
function doSomethingIfArrIsNotEmpty(arr) {
    for (var i = 0; i < arr.length; i++) { // USELESS_LOOP alarm because the enclosing 'for' can be refactored to 'if'.
        doSomething(arr[i]);
        break;
    }
}

// Example 2
function getEnclosingTable(tdElem) {
    var elem = tdElem;
    while (elem.parentNode) { // USELESS_LOOP alarm because a condition is missing at the 'return' statement.
        elem = elem.parentNode;
        return elem;
    }
    throw new Error("No enclosing table");
}

Compliant Code Example

View with noncompliant examples side by side
// Example 1
function doSomethingIfArrIsNotEmpty(arr) {
    if (arr.length > 0) {
        doSomething(arr[0]);
    }
}

// Example 2
function getEnclosingTable(tdElem) {
    var elem = tdElem;
    while (elem.parentNode) {
        elem = elem.parentNode;
        if (elem.tagName === "TABLE") {
            return elem;
        }
    }
    throw new Error("No enclosing table");
}

Version

This rule was introduced in DeepScan 1.24.0.

Was this documentation helpful?