DEV Community

Cover image for Magic of Template Literals in JavaScript
Muhammed Shameel Maravan
Muhammed Shameel Maravan

Posted on

Magic of Template Literals in JavaScript

If you've been working with JavaScript, you've probably encountered situations where you need to concatenate strings or include variables within strings. Traditionally, this was done using the + operator or string concatenation methods. Enter template literals, a powerful feature introduced in ECMAScript 6 (ES6) that simplifies string manipulation and makes your code more readable.

What are template literals?

Template literals are a new way to work with strings in JavaScript. They are enclosed by backticks (``) instead of single or double quotes. This seemingly small change brings plenty of benefits, making your code cleaner and more expressive.

Here's a quick example:

`
// Traditional string concatenation
const name = "John";
const greeting = "Hello, " + name + "!";

// Using template literals
const greetingTemplate = Hello, ${name}!;

`
As you can see, template literals allow you to embed expressions within the string using ${} syntax. This not only looks cleaner but also improves the readability of your code.

Embedding Variables

One of the standout features of template literals is the ease with which you can embed variables into strings. This can be especially handy when creating dynamic content or messages.

`
const product = "JavaScript Magic Book";
const price = 29.99;

// Using template literals to embed variables
const productInfo = The ${product} is currently priced at $${price}.;

`
This makes your code more concise and eliminates the need for complex string concatenation.

Multi-line Strings

Say goodbye to awkward line breaks and concatenation for multi-line strings. Template literals support multi-line strings directly.

`
// Traditional multi-line string
const poem = "Roses are red,\nViolets are blue,\nSugar is sweet,\nAnd so are you.";

// Using template literals for multi-line strings
const poemTemplate =
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.
;
`
No more escaping newline characters or using tedious concatenation for multi-line text. Template literals make it easy to maintain the structure of your strings.

Expressions and Functions
Template literals can handle more than just variables. You can embed expressions and even call functions directly within the template.

`
const x = 5;
const y = 10;

// Using expressions in template literals
const sumTemplate = The sum of ${x} and ${y} is ${x + y}.;

// Calling functions in template literals
function greet(name) {
return Hello, ${name}!;
}

const greetingMessage = greet("Alice");

`

This flexibility opens up new possibilities for creating dynamic and interactive strings.

Tagged Templates

For advanced use cases, JavaScript introduces tagged templates. These allow you to process template literals with a function, providing ultimate customization.

`
function customTag(strings, ...values) {
// Process the strings and values as needed
return "Processed result";
}

const result = customTagThis is ${x} and ${y}.;
`
Tagged templates give you fine-grained control over the generated string, making them a powerful tool in your JavaScript toolkit.

Conclusion

Template literals bring a breath of fresh air to string manipulation in JavaScript. They offer a cleaner syntax, better readability, and enhanced features for dynamic content creation. Whether you're a beginner or an experienced developer, incorporating template literals into your code can lead to more maintainable and expressive solutions.

In your journey with JavaScript, let template literals be your companion, simplifying the way you handle strings and making your code more enjoyable to write and read.

Happy coding!

Top comments (1)

Collapse
 
eugenioenko profile image
Eugene Yakhnenko

The most magical usage of template literals is comparing two arrays of primitive values. Example, you can compare two array of strings like this

const a = ['one', 'two', 'three'];
const b = ['one', 'two', 'three'];
const equal = `${a}` === `${b}`;
Enter fullscreen mode Exit fullscreen mode

In the snippet above, we leverage the implicit conversion of Array.toString method and then compare both results.
Very important to note, this works with primitive types only: numbers, strings and booleans;
When used with objects, this will fail because [Object object] === [Object object]