Skip to content
Start » Web development » How to fix ESLint error 'Unexpected string concatenation'

How to fix ESLint error 'Unexpected string concatenation'

When running ESLint in a Javascript, NodeJs or ExpressJs code, we may encounter the error of “unexpected string concatenation” or “Unexpected string concatenation”.

This lint points to possible code that handles string concatenation, which was written in such a way as to be difficult to read.

Fixing ESLint error “Unexpected string concatenation”

In addition to being able to change the configuration of your lint, to correct the error “Unexpected string concatenation” (unexpected string concatenation) when using ESLint as lint in our JavaScript project, we should use Template Literals (template literals) instead of direct string concatenation.

For example, if we write:

const LABEL = 'with special house recipe' const especial = [ { cName: 'House pizza', oSubMenu: [{ cName: `Pizza ${LABEL}`, cValue: `R$ 37.00` }, { cName: 'Noodles da casa', theSubMenu: [{ cName: `Noodles ${LABEL}`, cValue: `R$ 17.00` }] }]

When we use back quotes to delimit a string, it interpolates variables and functions that will be executed and are called substitutions.

In this way, in the example, the variables cName will have the portion of their strings contained between the dollar sign and the braces, interpolated to the value corresponding to the constant LABEL.

So, for the first position of the array Special, the variable cName will have the value: Pizza with house special recipe. While the same variable in the second position will have the value: Pasta with house recipe.

It is also possible to use expressions in Template Literals to simplify the construction of strings.

See the code below:

const icms = 0.12 const shipping = 100 const product = 1500 console.log('The value of the product is ' + product + ', the icms is ' + (product*icms) + ', and the value of shipping is ' + shipping )

You can improve readability and decrease code length by using template literals:

const icms = 0.12 const shipping = 100 const product = 1500 console.log(`The value of the product is ${product}, the icms is ${product*icms}, and the value of shipping is ${shipping}.`)

Our second code makes the variables and expressions or functions more explicit in the string assembly, being possible to identify them delimited by ${ }.

It also allows a more direct reading of the code without having to decipher where the string starts or ends within the delimiters of the sets of single quotes concatenated with the plus signs.

Conclusion

To fix the “Unexpected string concatenation” error when we are using ESLint to lint our JavaScript project, and also to improve the readability and quality of our code, we should use Template Literals instead of string concatenation.

Leave a Reply

Your email address will not be published.

en_USEnglish
%d bloggers like this: