Variables & Data Lesson 8 of 30
JavaScript Strings and Template Literals
Work with text in JavaScript — quotes, escape characters, string length, joining text, and template literals with ${} for clean messages.
Most of what a website shows is text: names, messages, labels, receipts. In JavaScript, text is stored as a string. This lesson covers how to write strings and build messages from them.
Writing strings
const a = "Double quotes";
const b = 'Single quotes';
const c = `Backticks (template literal)`;
The first two are the same. The third kind, with backticks, has superpowers you'll see below.
Length of a string
.length tells you how many characters a string has, including spaces:
<p id="out"></p>
<script>
const name = "Andres Bonifacio";
document.getElementById("out").textContent =
name + " has " + name.length + " characters.";
</script>
Escape characters
A backslash \ gives the next character a special meaning:
| Code | Result |
|---|---|
\" | A double quote inside a double-quoted string |
\' | A single quote inside a single-quoted string |
\\ | A real backslash |
\n | New line |
\t | Tab |
const line = "She said, \"Kaya natin 'to!\"";
const path = "C:\\Users\\Juan";
Joining strings
You can join strings with +, but long messages get messy fast:
const msg = "Hi " + name + "! Your average is " + avg + " and you are in " + section + ".";
Template literals
A template literal uses backticks and lets you put values directly inside with a dollar sign and curly braces. The same message becomes much cleaner:
<pre id="out"></pre>
<script>
const name = "Gabriela";
const avg = 92.5;
const section = "Mabini";
const msg = `Hi ${name}! Your average is ${avg} and you are in ${section}.`;
const next = `Next year you'll be in Grade ${9 + 1}.`;
document.getElementById("out").textContent = msg + "\n" + next;
</script>
Anything inside the curly braces is computed first, so you can even do math, like ${9 + 1} or ${price * qty}.
Multi-line text
Template literals can also span several lines without \n:
<pre id="out"></pre>
<script>
const item = "Pandesal";
const qty = 10;
const price = 2.5;
document.getElementById("out").textContent = `RESIBO
-------------------
${qty} × ${item} @ ₱${price}
Total: ₱${qty * price}
Salamat po!`;
</script>
Getting one character
Each character has a position number called an index, and counting starts at 0:
const word = "Pilipinas";
word[0] // "P"
word[1] // "i"
word[word.length - 1] // "s" (the last character)
Strings can't be changed in place
word[0] = "p" does nothing. Strings are immutable: you can't edit them, only create new ones. String methods like toUpperCase() always return a new string. That's the next lesson.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04