Answer a Question
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.

Instructions

  • Do:

    prefer template literals for string definition and concatenation

  • Avoid:

    string concatenation using the plus operator

Avoid

string concatenation using plus operator

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

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

Do

prefer template literals

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

const displayName = `${user.firstName} ${user.lastName}`.trim();
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

Whoa 🤚 You need to sign in to join the discussion.

Don't worry, if you start a comment, we'll save it for when you return. 😉