By executing ESLINT in a JavaScript code, Nodejs or Expressjs, we can find the error “unexpected string concatenation” or “Unexpeted String Concatenation”.
This lint points to a possible code that manipulates string concatenation, which was written in order to result in a difficult reading.
Solving the Eslint error Unexpected string concatenation
In addition to being able to change your LINT configuration to correct the error “Unexpeted String Concatenation” when using Eslint as the linter in our JavaScript project, we should use <a href = “https://developer.mozilla.org/en-us/docs/web/javascript/reference/template_litals “target =”_ blank “rel =“noreferrer noopener”>Literal template (model literals) instead of straight string concatenation.
For example, consider the code:
const LABEL = ' with special home recipe'
const special = [
{
cName: 'Special Pizza',
oSubMenu: [{
cName: `Pizza ${ROTULO}`,
cValue: `$ 37.00`
},
{
cName: 'Scpecial Pasta',
oSubMenu: [{
cName: `Pasta ${ROTULO}`,
cValue: `$ 17.00`
}]
}]
When we use the inverse quotes to delimit a string, it interpolate variables and functions that will be performed and are called substitutions.
In this way, in the example, the cName
variables will have the portion of their strings contained between the dollar signal and the keys, interpolated to the value corresponding to the constant LABEL
.
Therefore, for the first position of the Array special
, the variable cName
will have the value: Special Pizza with special home recipe
. While the same variable in second position will have the value: Special Pasta with special home recipe
.
Literal template expressions can also be used to simplify string construction.
See the following code:
const vat = 0.12
const shipping = 100
const product = 1500
console.log('The product value is ' + product + ', the vat ' + (product*vat) + ', and the shipping value is ' + shipping)
It is possible to improve its readability and decrease code extension using model literals:
const vat = 0.12
const shipping = 100
const product = 1500
console.log(`The product value is ${product}, the vat is ${product*vat}, and the shipping value is ${shipping}.`)
Our second piece of code read the variables and expressions or functions are more explicit in the building of the string, and it is possible to identify them delimited by ${}
.
It also allows a more direct reading of the code without the need to decipher where the string starts or ends among the delimitations of the simple marked marks of concatenated marks with the additions of plus signal.
Final considerations
To correct the error of “UNEXPEDED STRING CONCATEANATION” when we are using Eslint for Lint our JavaScript project, as well as to improve the readability and quality of our code, we must use literal template instead of string concatenation.
Comments