arrow-left arrow-right brightness-2 chevron-left chevron-right facebook-box facebook loader magnify menu-down rss-box star twitter-box twitter white-balance-sunny window-close
JavaScript (ES6)+ : String Concatenation with Template Literals
1 min read

JavaScript (ES6)+ : String Concatenation with Template Literals

JavaScript (ES6)+ : String Concatenation with Template Literals

Have you ever ran into code that looks something like this?

const firstName = "Paul"
const lastName = "Halliday"

const greeting = "Hello, my name is " + firstName + " " + lastName

// Hello, my name is Paul Halliday

In order to combine the firstName and lastName into a greeting, we're using the + operator.

Whilst this works in practice, it's kind of annoying because we have to manually add spaces, whitespace, and then remember to concatenate our next variable.

Thankfully, there's a better way to do this.

String Interpolation using Backticks

We can use the backtick `` (found next to Z or 1) on your keyboard instead of quotes to concatenate strings as seen here:

const firstName = "Paul"
const lastName = "Halliday"

const greeting = `Hello, my name is ${firstName} ${lastName}`

Inside of our backticks we're using the ${expression} syntax, where expression resolves to the function or variable that we want to show.

Browser support

As always, you should be careful about using any new syntax without a compilation step/polyfill.

Here's the list of browsers that support this syntax: https://caniuse.com/#feat=template-literals