JavaScript String Templates
Template literals (string templates) allow you to embed variables and expressions directly into strings, improving readability and reducing the need for concatenation.
Key Topics
- Basic Template Literals
- Expressions in Templates
- Multi-line Strings
- JavaScript Usage in DOM
- Key Takeaways
Basic Template Literals
Use backticks (`
) and ${...}
placeholders to insert variables into strings.
let name = "John";
let greeting = `Hello, ${name}!`;
console.log(greeting);
Output
> Hello, John!
Explanation: Template literals allow inserting the name
variable directly into the string without concatenation.
Expressions in Templates
You can embed any valid JavaScript expression, including arithmetic and function calls, directly inside ${...}
.
let x = 5;
let y = 3;
console.log(`Sum: ${x + y}`);
Output
> Sum: 8
Explanation: The expression x + y
is evaluated inside the template literal, resulting in "Sum: 8" without separate concatenation steps.
Multi-line Strings
Template literals support multi-line strings without special escape characters, improving code readability.
let text = `This is a
multi-line
string.`;
console.log(text);
Output
> This is a
> multi-line
> string.
Explanation: Using backticks preserves line breaks, making it simpler to write and maintain long or formatted strings.
JavaScript Usage in DOM
This DOM-based example demonstrates using template literals to insert dynamic data into the webpage easily.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Templates in DOM</title>
</head>
<body>
<h1>Template Literals Demo</h1>
<button onclick="showInfo()">Show Info</button>
<p id="info"></p>
<script>
function showInfo() {
let user = "Alice";
let age = 28;
document.getElementById("info").textContent = `Name: ${user}, Age: ${age}`;
}
</script>
</body>
</html>
Key Takeaways
- Variable Insertion: Use
${...}
to embed variables and expressions. - Expressions: Perform calculations directly inside template literals.
- Multi-line Strings: Easily write and maintain multi-line strings.
- DOM Integration: Dynamically display user data without complex concatenation.