00

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

Code Examples

prefer template literals

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

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

string concatenation using plus operator

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

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

I am a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. I regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, I enjoy skiing, hiking, and being in the outdoors. I started lookout.dev to break down the barriers of learning in public. Learning in public fosters growth - for ourselves and others.

Google Developers Expert

Discussions are healthy ❤️