#atom
ID: JS-001
Date: [Insert Date]
Content:
Template literals are a feature in JavaScript (introduced in ES6) that allow for easier string creation and manipulation. They are enclosed by backticks (`
) instead of single or double quotes and support multi-line strings, string interpolation, and embedded expressions.
Key Features:
-
Multi-line Strings:
Template literals preserve newlines and whitespace, making it easy to create multi-line strings without using\n
.const multiLine = ` This is a multi-line string. `;
-
String Interpolation:
Variables and expressions can be embedded directly into the string using${}
.const name = 'Alice'; const greeting = `Hello, ${name}!`; // "Hello, Alice!"
-
Embedded Expressions:
Any valid JavaScript expression can be placed inside${}
.const a = 5; const b = 10; const result = `The sum of ${a} and ${b} is ${a + b}.`; // "The sum of 5 and 10 is 15."
-
Tagged Templates:
Template literals can be processed by a function (called a "tag") for advanced string manipulation.function tag(strings, ...values) { return strings.reduce((result, str, i) => { return result + str + (values[i] || ''); }, ''); } const name = 'Alice'; const age = 25; const message = tag`Hello, ${name}! You are ${age} years old.`; console.log(message); // "Hello, Alice! You are 25 years old."
Advantages:
- Cleaner syntax for string interpolation and multi-line strings.
- Improved readability and maintainability of code.
Connections:
Connections:
Sources: