Template Strings
Template strings are a much cleaner way of embedding variables and expressions within strings as opposed to using string concatenation.
Syntax
Notice the use of back-ticks (``
) in the example below, along with the expression contained within the dollar-sign and curly brace combo (${}
).
`this is a string`
`this is a string with an ${expression}`
Real World Examples
Here we can create a simple loop that will iterate over an array and return a template string containing the current name.
const names = ['Tim', 'Andrea', 'Lisa', 'John', 'Julie', 'Jack'];
for (var i in names) {
console.log(`Hello, ${names[i]}`)
}
Test this code in your browser console
Using template strings is typically a much faster and cleaner alternative to string concatenation. It's particularly noticeable when you have a string with a lot of variables. For instance:
const founder = {
firstName: "Richard",
lastName: "Branson",
age: 68,
company: "Virgin Group"
}
const { firstName, lastName, age, company } = founder;
// example using string concatenation
console.log(firstName + " " + lastName + " is the founder of " + company + " and is " + age + " years old.");
// example using template strings
console.log(`${firstName} ${lastName} is the founder of ${company} and is ${age} years old.`);
Test this code in your browser console
Wrapping Up ✅
Not only are template strings much easier to read, they're far easier to write. There's no need to worry about closing the string before adding your variable or making sure you add spaces where they should be. Template strings allow for (nearly) natural sentences without all the mess and complication that you'd get with the equivalent string concatenation.
Stay Tuned 📺
If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at tim@timwheeler.com
. If you're enjoying my posts, please click here 📬 or subscribe below 👇!