Simplifying String Handling with JavaScript Template Literals

In today's article, I want to talk about something incredibly powerful and fun to use in JavaScript: template literals! When template literals first came onto my radar, it was a definite "wow" moment.


If you've ever been tangled up in a messy string concatenation or scratched your head over a multiline string, this one's for you.

Let's dive into the simplicity and power of template literals in JavaScript.

The Basics of Template Literals

So, what are template literals? Template literals are a fresh approach to handling strings in JavaScript. You can use multi-line strings and string interpolation features with them. Instead of single (') or double (") quotes, you use backticks ( `).

let greeting = `Hello, world!`; 

console.log(greeting); // outputs: Hello, world!

Here, we just created a string using template literals!

Multiline Strings with Template Literals

Writing multiline strings can get messy with traditional quotes. Thankfully, template literals make it super easy. Just hit Enter to go to the next line:

let quote = `
In the midst of chaos, 
there is also opportunity.


This outputs the string exactly as you typed it, new lines and all.

Expression Interpolation in Template Literals

Now comes the fun part: putting JavaScript expressions inside your strings. This is called 'interpolation'. Here's how it works:

let x = 5; 
let y = 10; 

console.log(`The sum is ${x + y}.`); // outputs: The sum is 15.

It gets even more exciting when we incorporate conditions within our expressions. This is a great way to write dynamic strings that react to the data they hold. For instance, let's consider a shopping scenario:

var qty = 7;
var cart = `You have ordered ${qty} ${qty > 1 ? "bottles" : "bottle"} of milk.`;

console.log(cart) // "You have ordered 7 bottles of milk."

Tagged Template Literals

Let's go a bit advanced: meet tagged templates. They let you parse a template literal with a function. Here's a simple example:

function myString(strings, nameExp) {
  let str0 = strings[0]; // "Hello "
  let str1 = strings[1]; // ", how are you?"

  return `${str0}${nameExp}${str1}`;

let name = 'John';

let output = myString`Hello ${ name }, how are you?`;

console.log(output); // Outputs: Hello John, how are you?

With tagged templates, your template literals are even more powerful.

That's a wrap on our exploration of JavaScript template literals.

From simple string formatting to complex tagged templates, template literals offer a lot of power in a small package. You're sure to love their simplicity and power.

Remember, the best way to learn is by doing.

Avatar for Patrick Hladun

Written by Patrick Hladun

I'm a Frontend Developer and WordPress enthusiast on a mission to constantly improve my skills and keep up with the latest technology trends.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.