Strings & Template Literals
Work with text — joining, and the modern back-tick syntax that makes building strings a joy.
What you will learn
- Create and join strings
- Use template literals with back-ticks
- Embed variables inside text
Strings and joining
A string is text in quotes. Join strings with + (called concatenation).
<script>
let first = "Asha";
let last = "Rao";
document.write(first + " " + last);
</script>We glue three pieces together with +: the first name, a " " (a single space, so the words do not run together), and the last name. The result is one combined string.
Note: Output: Asha Rao
Template literals — the modern way
Template literals use back-ticks ( ` ) instead of quotes, and let you drop variables right inside the text with ${ }. Much cleaner than +.
<script>
let name = "Asha";
let score = 95;
document.write(`${name} scored ${score}% 🎉`);
</script>Inside the back-ticks, each ${ } is a hole that gets filled with a variable. ${name} becomes "Asha" and ${score} becomes 95, and the rest of the text ("scored", "%", the emoji) stays exactly as written. No + and no fiddly spaces needed.
Note: Output: Asha scored 95% 🎉
Template literals can also span multiple lines without any special characters.
<script>
let city = "Bengaluru";
let msg = `Welcome to CodingClave.
You are learning in ${city}.`;
document.write(msg.replace("\n", "<br>"));
</script>Because the text is wrapped in back-ticks, the line break you see in the code is kept as a real line break in the string. ${city} fills in "Bengaluru". The .replace("\n", "<br>") at the end swaps that line break for an HTML <br> so the browser shows it on two lines.
Note: Output: Welcome to CodingClave. You are learning in Bengaluru.
Tip: Template literals (back-ticks with ${ }) are the modern standard and are used heavily in React. Prefer them over + for readability.
Q. What character starts and ends a template literal?
✍️ Practice
- Build a greeting using a template literal that includes your name and city.
- Convert a
+concatenation into a template literal.
🏠 Homework
- Write a function that returns a sentence built with a template literal from three parameters.