About Lesson
JavaScript Template Strings
Template strings, also known as template literals, allow for easier string interpolation and multiline strings in JavaScript. They are enclosed within backticks (``
) instead of single or double quotes.
Basic Usage
You can embed expressions and variables directly within template strings using the ${}
syntax.
Example:
const name = "John";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!
Multiline Strings
Template strings support multiline strings without the need for escape characters like newline (\n
).
Example:
const multilineString = `
This is a
multiline string
without needing
escape characters.
`;
console.log(multilineString);
Expression Interpolation
Template strings allow you to embed expressions directly within the string.
Example:
const num1 = 5;
const num2 = 10;
const result = `The sum of ${num1} and ${num2} is ${num1 + num2}.`;
console.log(result); // Output: The sum of 5 and 10 is 15.
Template strings provide a more flexible and readable way to work with strings in JavaScript, especially when dealing with complex string concatenations or multiline strings.