| let, const, arrow functions | Destructuring | |
Template Literals in JavaScript |
Template literals are a modern feature in JavaScript (ES6) that allow for advanced string manipulation, such as embedding expressions and creating multiline strings. Unlike traditional strings enclosed in single (') or double (") quotes, template literals use backticks (`).
Template literals are string literals enclosed by `backticks` instead of single (') or double (") quotes. They support:
${expression}\nEnclose your string in backticks.
//javascript const greeting = `Hello, world!`; console.log(greeting); // Output: Hello, world!
Insert variables and JavaScript expressions directly into your string using the ${...} placeholder.
//javascript
const name = "Alice";
const age = 30;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // Output: My name is Alice and I am 30 years old.
//javascript
const a = 10;
const b = 5;
const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // Output: The sum of 10 and 5 is 15.
Template literals also allow for embedding function calls within the ${...} placeholder.
Template literals can span multiple lines without needing escape characters, preserving the line breaks within the backticks. You can see an example in the referenced document.
// Basic interpolation
const name = "Shivshanker";
console.log(`Hello, ${name}!`);
// Multi-line string
const poem = `Roses are red,
Violets are blue,
Template literals,
Make coding new.`;
// Expression evaluation
const a = 5, b = 10;
console.log(`Sum: ${a + b}`);
// Tagged template
function emphasize(strings, ...values) {
return strings.reduce((acc, str, i) => acc + str + (values[i]?.toUpperCase() || ""), "");
}
const mood = "excited";
console.log(emphasize`I am feeling very ${mood} today!`);
Template literals improve code readability by simplifying string interpolation and making multiline strings easy to create. They also allow the use of single and double quotes within the string without requiring escaping.
While typically negligible, there might be a slight performance overhead compared to simple string literals. For very basic, static strings, standard quotes might be more immediately understandable to some developers. Additionally, using template literals for dynamic content like SQL queries or HTML requires careful handling to prevent security vulnerabilities.
Template literals are best used for complex string formatting involving variables or expressions, creating multiline text, and generating dynamic content like HTML or SQL queries. However, when building dynamic queries, be sure to take precautions against SQL injection attacks.
For simple, static strings without any variables or expressions, using standard single or double quotes can be clearer. Also, avoid using them in environments that don't support ES6 if compatibility with very old browsers is necessary.
Use template literals for dynamic and multiline strings, reserving standard quotes for static ones. Remember to escape literal backticks (`) or dollar signs ($) with a backslash if needed. It is crucial to sanitize any user input embedded within template literals to prevent security risks like Cross-Site Scripting (XSS) or SQL injection. For more complex scenarios, you can nest template literals or use tagged templates for more control over string processing.
${} simple and readable+ for string concatenationconsole.log(`User ${user.name} logged in at ${new Date().toISOString()}`);
const items = ['apple', 'banana'];
console.log(`Shopping list:\n${items.map(i => `- ${i}`).join('\n')}`);
| let, const, arrow functions | Destructuring | |