All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.javascript.rules.javascript.S1472.html Maven / Gradle / Ivy

There is a newer version: 10.20.0.29356
Show newest version

Why is this an issue?

JavaScript will automatically insert semicolons when parsing the code so invalid sequences can be "fixed" to valid syntax. This behavior, called "Automatic semicolon insertion" or ASI, makes semicolons at the end of statements optional and attempts to make JavaScript more approachable and convenient.

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.

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 IIFE (or any other design pattern using Grouping operator), it can lead to errors and most likely will lead to questions for maintainers.

What was the initial intent of the developer?

  1. Defining a function and then executing some unrelated code inside a closure?
  2. Passing the second function as a parameter to the first one?

The first option will be the one chosen by the JavaScript interpreter.

const fn = function () {
  //...
}

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

By extension, and to improve readability, any kind of function call argument should not start on a new line.

// Define a function
const fn = function () {
  //...
}; // <-- semicolon added

// then execute some code inside a closure
(function () {
  //...
})();

Or

var fn = function () {
  //...
}(function () { // <-- start function call arguments on same line
  //...
})();

Similarly, tagged templates allow for advanced forms of string interpolation by evaluating the tag as a function to call, passing the template literal elements as arguments.

const foo = function() {
  return 'foo';
}

`bar`; // Noncompliant: `bar` passed as a parameter to function. foo is a string, not a function

Therefore, the rule also verifies that template literals don’t start on a separate line.

function foo() {  // <-- Use a function declaration
  return 'foo';
}

`bar`;

Or

const foo = function() {
  return 'foo';
}`bar`; // <-- start template literal on same line

Resouces

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy