New Best Practice
Sign In

Prefer Template Literals over String Concatenation

Thursday, February 20, 2020

ECMAScript version 2015 (aka ES6) introduced template literals using the backtick (or grave accent) mark that supports multiline strings, expression interpolation, nesting templates, and tagged templates. The rich features of template literals vastly improves upon the use of strings marked using either single or double quotes in JavaScript. As such, it is recommended that template literals are used over string concatenation. Further, if your application must support older versions of ECMAScript then it is recommended that you use a transpiler such as Babel or TypeScript.

Code Examples

const user = {
  firstName: 'Brian',
  lastName: 'Love'
}

const displayName = (user.firstName + ' ' + user.lastName).trim();

avoid: string concatenation using plus operator

const user = {
  firstName: 'Brian',
  lastName: 'Love'
}

const displayName = `${user.firstName} ${user.lastName}`.trim();

do: prefer template literals

Instructions

  • Do:

    prefer template literals for string definition and concatenation

  • Avoid:

    string concatenation using the plus operator

Brian Love

Brian is a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. He regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, Brian enjoys skiing, hiking, and being in the outdoors. Brian recently launched lookout.dev where you can find best practices and expert advice on topics ranging from TypeScript, Angular, React, Node.js and more.

Google Developers Expert

Discussions are healthy ❤️