Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3758

Values not convertible to numbers should not be used in numeric comparisons

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
      None
    • Message:
      Re-evaluate the data flow; this operand of a numeric comparison could be {"undefined"|an Object}.
    • Highlighting:
      Hide

      Primary: Expression
      Secondary: Path that puts comparison var in bad state

      Show
      Primary: Expression Secondary: Path that puts comparison var in bad state
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way recommended
    • Covered Languages:
      JavaScript
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      In a Zen-like manner, NaN isn't equal to anything, even itself. So comparisons (>, <, >=, <=) where one operand is NaN or evaluates to NaN always return false. Specifically, undefined and objects that cannot be converted to numbers evaluate to NaN when used in numerical comparisons.

      This rule raises an issue when there is at least one path through the code where one of the operands to a comparison is NaN, undefined or an Object which cannot be converted to a number.

      Noncompliant Code Example

      var x;  // x is currently "undefined"
      if (someCondition()) {
        x = 42;  
      }
      
      if (42 > x) {  // Noncompliant; "x" might still be "undefined"
        doSomething();
      }
      
      var obj = {prop: 42};
      if (obj > 24) { // Noncompliant 
        doSomething();
      }
      

      Compliant Solution

      var x;
      if (someCondition()) {
        x = 42;
      } else {
        x = foo();
      }
      
      if (42 > x) {
        doSomething();
      }
      
      var obj = {prop: 42};
      if (obj.prop > 24) {
        doSomething();
      }
      

        Attachments

          Activity

            People

            Assignee:
            elena.vilchik Elena Vilchik
            Reporter:
            jeanchristophe.collet Jean-Christophe Collet (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated: