Skip to content

Template literals JavaScript

  • by

Template literals in JavaScript are a feature introduced in ES6 that allows for the creation of string literals with placeholders or expressions. Using backticks instead of quotes, developers can easily interpolate variables and create dynamic strings.

Template literals JavaScript example

Simple example code creates a template literal in JavaScript, you can use backticks (`) instead of single or double quotes.

Back-Tics Syntax

This is used to denote template literals, which are a way of creating strings that can contain placeholders or expressions. Back-ticks allow for string interpolation, which means that variables and expressions can be included within the string without the need for concatenation.

const name = 'John';
const age = 25;

const greeting = `Hello, my name is ${name} and I'm ${age} years old.`;
console.log(greeting)

Output:

Template literals JavaScript

Quotes can be used inside strings by using a different type of quote to enclose the string, or by escaping the quote character within the string.

For example, if you want to include a single quote character inside a string that is enclosed by single quotes, you can use double quotes to enclose the string:

const myString = 'She said "Hello"';

Similarly, if you want to include a double quote character inside a string that is enclosed by double quotes, you can use single quotes to enclose the string:

const myString = "He said 'Goodbye'";

Multiline Strings

Multiline strings can be created using template literals or by concatenating multiple strings together. To create a multiline string using template literals, enclose the string within backticks (`) and use line breaks to create new lines in the string.

const myString = `This is a
multiline
string.`;

Interpolation

Interpolation is the process of inserting a value or expression into a string. To interpolate a value or expression into a template literal, you enclose the value or expression within ${}.

const name = "Alice";
const age = 30;

const message = `My name is ${name} and I'm ${age} years old.`;

Comment if you have any doubts or suggestions on this JS basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *