
* Modify rule S1472: Add tagged template literals * Copy general descrition to javascript description to add the template literal use-case * Update rules/S1472/javascript/rule.adoc Co-authored-by: Yassin Kammoun <52890329+yassin-kammoun-sonarsource@users.noreply.github.com>
91 lines
1.9 KiB
Plaintext
91 lines
1.9 KiB
Plaintext
Because semicolons at the ends of statements are optional, starting function call arguments on a separate line makes the code confusing. It could lead to errors and most likely _will_ lead to questions for maintainers.
|
|
|
|
|
|
What was the initial intent of the developer?
|
|
|
|
. Define a function and then execute some unrelated code inside a closure ?
|
|
. Pass the second function as a parameter to the first one ?
|
|
|
|
The first option will be the one chosen by the JavaScript interpreter.
|
|
|
|
|
|
By extension, and to improve readability, any kind of function call argument should not start on new 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. Therefore, the rule also verifies that template literals don't start on a separate line.
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,text]
|
|
----
|
|
const fn = function () {
|
|
//...
|
|
}
|
|
|
|
(function () { // Noncompliant
|
|
//...
|
|
})();
|
|
|
|
const foo = function() {
|
|
return 'foo';
|
|
}
|
|
|
|
`bar`; // Noncompliant: foo is a string not a function
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
Either
|
|
|
|
|
|
[source,text]
|
|
----
|
|
// define a function
|
|
const fn = function () {
|
|
//...
|
|
}; // <-- semicolon added
|
|
|
|
// then execute some code inside a closure
|
|
(function () {
|
|
//...
|
|
})();
|
|
|
|
function foo() { // <-- Use a function declaration
|
|
return 'foo';
|
|
}
|
|
|
|
`bar`;
|
|
----
|
|
|
|
Or
|
|
|
|
[source,text]
|
|
----
|
|
var fn = function () {
|
|
//...
|
|
}(function () { // <-- start function call arguments on same line
|
|
//...
|
|
})();
|
|
|
|
const foo = function() {
|
|
return 'foo';
|
|
}`bar`; // <-- start template literal on same line
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
include::../highlighting.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|