Template Literals in JavaScript

Template literals are strings written using backticks (`) that allow variables and expressions to be embedded directly. Introduced in ES6, they make strings more readable and support easy interpolation and multi-line text without complex concatenation.
Use backticks (`) to embed variables and expressions directly in strings.
Introduced in ES6, they support easy interpolation and multi-line strings.
let a='GFG'
console.log(`hello ${a}`)
Embedding variables: Template literals like hello ${a} insert variable values directly into strings, producing output such as hello GFG.
Cleaner concatenation: They avoid using +, making string creation more readable and easier to write.
Syntax:
`Text before ${variableOrExpression} text after`
Backticks (``): Used to define a template literal.
${}: Used to insert expressions inside the string, such as variables, function calls, or arithmetic operations
String Interpolation with Expressions
String interpolation lets you insert not just variables but also expressions, like math operations or function results, directly into a string.
let x = 5;
let y = 10;
console.log(`The sum of \({x} and \){y} is ${x + y}`);
Expression evaluation: Inside ${}, expressions like x + y are evaluated, and the result is inserted into the string.
Dynamic string creation: This technique allows you to dynamically create strings by combining variables and expressions, making the code cleaner and easier to read.
Multi-line Strings with Template Literals
Template literals allow you to create multi-line strings easily without needing escape characters like \n.
const s = `This is a multi-line
string that spans across
several lines.`;
console.log(s);
Multi-line support: Template literals preserve line breaks, so the string appears exactly as it’s written, making multi-line strings easier to handle.
No need for escape characters: You don’t need to use \n to break lines within the string; template literals automatically handle it.
Tagged Template Literals
Tagged template literals allow you to customize how the string is processed, providing more control over string creation.
creation.
function greet(strings, name) {
return \({strings[0]}\){name.toUpperCase()}${strings[1]};
}
const name = 'gfg';
console.log(greetHello, ${name}!);
In this code the string Hello,! is passed as an array in which the 0th index contains Hello, and the second index contains !
In the second parameter name is passed as gfg which is then converted to uppercase and then finally the concatenated content of the array and the value of the name parameter is combined and returned by the function.
Escaping Backticks and Dollar Signs
In JavaScript, if you need to include backticks or dollar signs inside template literals, you can escape them using a backslash ().
const s = This is a backtick: \ and this is a dollar sign: $`;
console.log(s);
Parameters
The string text that will become part of the template literal. Almost all characters are allowed literally, including line breaks and other whitespace characters. However, invalid escape sequences will cause a syntax error, unless a tag function is used.
An expression to be inserted in the current position, whose value is converted to a string or passed to tagFunction.
If specified, it will be called with the template strings array and substitution expressions, and the return value becomes the value of the template literal. See tagged templates.
Description
Template literals are enclosed by backtick (`) characters instead of double or single quotes.
Along with having normal strings, template literals can also contain other parts called placeholders, which are embedded expressions delimited by a dollar sign and curly braces: ${expression}. The strings and placeholders get passed to a function — either a default function, or a function you supply. The default function (when you don't supply your own) just performs string interpolation to do substitution of the placeholders and then concatenate the parts into a single string.
To supply a function of your own, precede the template literal with a function name; the result is called a tagged template. In that case, the template literal is passed to your tag function, where you can then perform whatever operations you want on the different parts of the template literal.
To escape a backtick in a template literal, put a backslash (\) before the backtick.
\`` === ""; // true
Dollar signs can be escaped as well to prevent interpolation.
\\({1} === "\){1}"; // true
Multi-line string
Any newline characters inserted in the source are part of the template literal.
Using normal strings, you would have to use the following syntax in order to get multi-line strings:
console.log("string text line 1\nstring text line 2");
// "string text line 1 // string text line 2"
Using template literals, you can do the same with this:
console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"
Like normal string literals, you can write a single-line string across multiple lines for source code readability, by escaping the newline with a backslash (\):
console.log(`string text line 1 \
string text line 2`);
// "string text line 1 string text line 2"
String interpolation
Without template literals, when you want to combine output from expressions with strings, you'd concatenate them using the addition operator +:
const a = 5;
const b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."
That can be hard to read – especially when you have multiple expressions.
With template literals, you can avoid the concatenation operator — and improve the readability of your code — by using placeholders of the form ${expression} to perform substitutions for embedded expressions:
const a = 5;
const b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."
Note that there's a mild difference between the two syntaxes. Template literals coerce their expressions directly to strings, while addition coerces its operands to primitives first. For more information, see the reference page for the + operator.
Nesting Templates
In certain cases, nesting a template is the easiest (and perhaps more readable) way to have configurable strings. Within a backtick-delimited template, it is simple to allow inner backticks by using them inside an ${expression} placeholder within the template.
For example, without template literals, if you wanted to return a certain value based on a particular condition, you could do something like the following:
let classes = "header";
classes += isLargeScreen()
? ""
: item.isCollapsed
? " icon-expander"
: " icon-collapser";
With a template literal but without nesting, you could do this:
const classes = `header ${
isLargeScreen() ? "" : item.isCollapsed ? "icon-expander" : "icon-collapser"
}`;
Raw Strings
The special raw property, available on the first argument to the tag function, allows you to access the raw strings as they were entered, without processing escape sequences.
function tag(strings) {
console.log(strings.raw[0]);
}
tag`string text line 1 \n string text line 2`;
// Logs "string text line 1 \n string text line 2",
// including the two characters '\' and 'n'
In addition, the String.raw() method exists to create raw strings just like the default template function and string concatenation would create.
const str = String.raw`Hi\n${2 + 3}!`;
// "Hi\\n5!"
str.length;
// 6
Array.from(str).join(",");
// "H,i,\\,n,5,!"
String.raw functions like an "identity" tag if the literal doesn't contain any escape sequences. In case you want an actual identity tag that always works as if the literal is untagged, you can make a custom function that passes the "cooked" (i.e., escape sequences are processed) literal array to String.raw, pretending they are raw strings.
const identity = (strings, ...values) =>
String.raw({ raw: strings }, ...values);
console.log(identity`Hi\n${2 + 3}!`);
// Hi
// 5!
Tagged Tamplaets and escape sequences
In normal template literals, the escape sequences in string literals are all allowed. Any other non-well-formed escape sequence is a syntax error. This includes:
\followed by any decimal digit other than0, or\0followed by a decimal digit; for example\9and\07(which is a deprecated syntax)\xfollowed by fewer than two hex digits (including none); for example\xz\unot followed by{and followed by fewer than four hex digits (including none); for example\uz\u{}enclosing an invalid Unicode code point — it contains a non-hex digit, or its value is greater than10FFFF; for example\u{110000}and\u{z}


