How to Use Template Literal in JavaScript: Syntax and Examples
In JavaScript, use
template literals by enclosing text in backticks (``) instead of quotes. You can embed variables or expressions inside ${} within the template literal for easy string interpolation.Syntax
A template literal is enclosed by backticks (``). Inside it, you can insert variables or expressions using ${expression}. This allows dynamic string creation without concatenation.
``: Backticks to start and end the template literal.${}: Placeholder to embed JavaScript expressions.
javascript
const name = "Alice"; const greeting = `Hello, ${name}!`;
Example
This example shows how to use template literals to create a greeting message with a variable and an expression.
javascript
const name = "Bob"; const age = 25; const message = `My name is ${name} and I will be ${age + 1} next year.`; console.log(message);
Output
My name is Bob and I will be 26 next year.
Common Pitfalls
Common mistakes include using single or double quotes instead of backticks, which disables interpolation, and forgetting to use ${} around expressions.
Also, template literals preserve whitespace and new lines, which can cause unexpected formatting if not intended.
javascript
const name = "Eve"; // Wrong: using quotes disables interpolation const wrong = 'Hello, ${name}!'; console.log(wrong); // prints literally // Right: use backticks and ${} const right = `Hello, ${name}!`; console.log(right);
Output
Hello, ${name}!
Hello, Eve!
Quick Reference
Use template literals for:
- Embedding variables or expressions with
${} - Multi-line strings without escape characters
- Readable and concise string formatting
Key Takeaways
Use backticks (`) to create template literals in JavaScript.
Embed variables or expressions inside ${} for easy string interpolation.
Template literals support multi-line strings without extra syntax.
Avoid using quotes if you want to interpolate variables; use backticks instead.
Template literals preserve whitespace and new lines exactly as written.