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

"undefined" should not be passed as the value of optional parameters

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove this redundant "undefined".
    • Highlighting:
      Hide

      "undefined"

      Show
      "undefined"
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way, Sonar way recommended
    • Targeted languages:
      JavaScript
    • Covered Languages:
      TypeScript
    • Irrelevant for Languages:
      ABAP, C#, C, C++, Cobol, CSS, Flex, Go, HTML, Java, Objective-C, PHP, PL/I, PL/SQL, Python, RPG, Swift, T-SQL, VB.Net, VB6, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      1min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      Unlike in JavaScript, where every parameter can be omitted, in TypeScript you need to explicitly declare this in the function signature. Either you add ? in the parameter declaration and undefined will be automatically applied to this parameter. Or you add an initializer with a default value in the parameter declaration. In the latter case, when passing undefined for such parameter, default value will be applied as well. So it's better to avoid passing undefined value to an optional or default parameter because it creates more confusion than it brings clarity. Note, that this rule is only applied to the last arguments in function call.

      Noncompliant Code Example

      function foo(x: number, y: string = "default", z?: number) {
        // ...
      }
      
      foo(42, undefined); // Noncompliant
      foo(42, undefined, undefined); // Noncompliant
      foo(42, undefined, 5); // OK, there is no other way to force default value for second parameter
      

      Compliant Solution

      function foo(x: number, y: string = "default", z?: number) {
        // ...
      }
      
      foo(42);
      

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            alexandre.gigleux Alexandre Gigleux
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Dates

              Created:
              Updated: