javascript

Template Literals

Template literals allow for embedded expressions and help to solve the complex concatenation problem.

They are enclosed by a back-tick character (the button just below the escape key on your keyboard) and are represented by a dollar sign ($) and curly braces ( {} ).

The template literals feature is an ES6 addition in Javascript, and they provide an elegant alternative to the traditional concatenations, especially when the values to be paired are complex.

Concatenation is an English word that means “to join.” In the context of JavaScript and other similar programming languages, it refers to joining two or more strings together.

Before ES6, we had to use the plus sign (+) to concatenate strings. Template literals, however, provide a more modular and elegant way to achieve the same result.

Let’s compare these two methods and see how template literals stand out.

Example

let name = 'Lawson Luke';

//with traditional concatenation
console.log('My name is ' +name); //My name is Lawson Luke

//with template literals
console.log(`My name is ${name}`); //My name is Lawson

Now let’s make things a little complex, shall we?

let name = 'Lawson Luke';
let city = 'Abuja';
let country: 'Nigeria';

//with traditional concatenation
 console.log('My name is '+name + ' '+ 'I reside in '+ city + ', ' + country + '. Thank you.');

//with template literals
console.log(`My name is ${name}. I reside in ${country}, ${city}. Thank you.`);

Summary

Template literals in JavaScript offer a cleaner and more readable way to join strings compared to the traditional method of using the + sign

They allow for the embedding of expressions and variables directly within strings and make string creation more readable and flexible.

Recent Posts

Common React Errors

React makes building user interfaces easier, but certain errors appear repeatedly, especially when working with…

11 hours ago

C Programming Cheat Sheet

The C programming language is a foundational, general-purpose computer programming language created by Dennis Ritchie at Bell Labs in 1972. Originally developed to…

19 hours ago

Homebrew Tutorial

What Is Homebrew? Homebrew is a package manager for macOS and Linux that makes it easy to…

4 days ago

10 Ways to Loop Through a JavaScript Array

JavaScript gives you several ways to iterate over an array. Some are better for simple…

6 days ago

Build a Node JS Web Server

A web server is the software responsible for receiving requests from clients, processing those requests,…

1 week ago

Shell Prompt Tutorial

A shell prompt is the text displayed by a command-line shell to show that it is ready…

2 weeks ago