~/
hackweb.dev
JavaScript Template Literals
Quiz
⌘K
...
~/
/tutorials
/js/js-template-literals/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/3js-template-literals
Write
Preview
Diff
# JavaScript Template Literals Template literals use backticks instead of quotes, making strings cleaner and more readable. ## Basic Interpolation ```javascript // Old way let message = "Hello, " + name + "!"; // Template literal let message = `Hello, ${name}!`; ``` Use `${}` to embed any expression inside a string: ```javascript let age = 30; let info = `You are ${age} years old.`; let next = `Next year you'll be ${age + 1}.`; ``` ## Multi-line Strings ```javascript // Old way let msg = "Line 1\nLine 2\nLine 3"; // Template literal let msg = `Line 1 Line 2 Line 3`; ``` No need for `\n` — just press Enter. ## Expressions in `${}` ```javascript let price = 10; let quantity = 3; let total = `Total: $${price * quantity}`; let items = ["apple", "banana", "orange"]; let list = `Fruits: ${items.join(", ")}`; ``` **Tip:** Keep expressions simple. Complex logic belongs outside `${}`. ## Generating HTML ```javascript let users = ["Alice", "Bob", "Charlie"]; let html = `<ul> ${users.map(user => ` <li>${user}</li>`).join("\n")} </ul>`; ``` ## Complete Example: User Card ```javascript let name = "Alice"; let age = 30; let city = "New York"; let card = ` Name: ${name} Age: ${age} City: ${city} -------------------`; console.log(card); ``` ## Best Practices 1. **Use backticks** — For template literals, not regular quotes 2. **Use `${}` for interpolation** — Not string concatenation 3. **Use multi-line** — For readability 4. **Keep expressions simple** — Complex logic outside `${}` 5. **Combine with `.map()`** — For dynamic HTML generation ## Common Mistakes 1. **Using regular quotes** — Template literals need backticks 2. **Forgetting `${}`** — Variables won't be interpolated 3. **Complex logic inside `${}`** — Keep it simple 4. **Escaping backticks** — Use `\`` if you need a literal backtick 5. **Missing closing backtick** — Causes syntax errors
No changes yet
Reset to original
Submit suggestion
cancel