Search code examples
javascripteslinttemplate-literals

ESLint error about Unexpected String Concatenation


I have the following:

return (useWordBoundary ? subString.substr(0, subString.lastIndexOf(' ')) : subString) + '\u2026';

Eslint is rejecting my code saying:

Suggest using template literals instead of string concatenation. (prefer-template)

What is wrong with the above?


Solution

  • It's a style question really. In your example, there's arguably not a lot of benefit in using template literals:

    return `${useWordBoundary ? subString.substr(0, subString.lastIndexOf(' ')) : subString}\u2026`;
    

    In other situations, it makes code more readable:

    return `Hello, ${name}!`;
    
    // vs.
    
    return 'Hello, ' + name + '!';
    

    If you choose to, you can selectively disable a rule for a specific line via a comment:

    // eslint-disable-next-line prefer-template
    return (useWordBoundary ? subString.substr(0, subString.lastIndexOf(' ')) : subString) + '\u2026';