What are templates and string literals in JavaScript?
sobes.tech AI
Answer from AI
Template literals (or template strings) are syntax for creating strings in JavaScript that offer several advantages over regular string literals (with single or double quotes).
Key features of template literals:
-
Multiline without special characters: You can create multiline strings simply by pressing Enter inside the template literal.
// Regular string with newline const classicString = 'String 1\nString 2'; // Template string with newline const templateString = `String 1 String 2`; -
Embedded expressions: Allow including JavaScript expressions directly within the string using the syntax
${expression}. The result of the expression will be interpolated into the string.const name = 'World'; const greeting = `Hello, ${name}!`; // greeting will be "Hello, World!" const sum = `Sum 2 + 3 equals ${2 + 3}.`; // sum will be "Sum 2 + 3 equals 5." -
Tagged templates: An advanced feature that allows calling a function (tag) before processing the template literal. The function receives an array of strings and the values of interpolated expressions, providing full control over string transformation.
function highlight(strings, ...values) { let result = ''; strings.forEach((str, i) => { result += str; if (values[i]) { result += `**${values[i]}**`; // Add highlighting } }); return result; } const item = 'JavaScript'; const description = highlight`Learning ${item} today!`; // description will be "Learning **JavaScript** today!"
Regular string literals use single ('...') or double ("...") quotes. They are simple and straightforward but require escape characters (\n for newline, \' or \" for including quotes of the same type inside the string) and concatenation (+) to combine variables or expressions with strings.
Template literals are denoted by backticks (`...`). They greatly improve code readability when working with strings, especially when including variables or creating multiline text.