Section 1 · First Steps
Strings and Template Literals
16 min3 min readCode playground
Lesson at a glance
Create and clean up strings, read characters by index, use the everyday string methods, and build readable output such as “Lunch: $12.20” with template literals.
- 1Writing strings
- 2Template literals: values inside text
- 3Characters, positions and slices
- 4Methods that return new strings
- 5Strings and numbers, back and forth
- 6Comparing strings
No video here — just the real thing: a written lesson, runnable examples, a quiz and practice.
Pocket’s numbers are exact now, but nobody wants to read 1220. People want Lunch: $12.20. Text in JavaScript is a string, and most of what a user ever sees from your program is a string you built.
Writing strings
You can write a string with single quotes, double quotes or backticks:
const a = 'Coffee';
const b = "Sam's lunch";
const c = `Bus`;
console.log(a, b, c);Single and double quotes behave the same; pick one style and stick to it (this course uses double quotes). Use the other kind when your text contains a quote, as in "Sam's lunch", or escape it with a backslash: 'Sam\'s lunch'. \n inside a string is a line break.
Backticks are special, and you will use them most. They make template literals.
Template literals: values inside text
Joining strings with + gets messy quickly: "Lunch: quot; + dollars + " (" + category + ")". It is easy to forget a space or a quote. A template literal lets you write the text once and drop values into it with ${ }:
const label = "Lunch";
const cents = 1220;
const category = "food";
const line = `${label}: ${(cents / 100).toFixed(2)} (${category})`;
console.log(line);Anything inside ${ } is a full JavaScript expression. It is evaluated, turned into a string, and inserted. Here (cents / 100).toFixed(2) divides to get 12.2, and toFixed(2) turns that into the string "12.20" with exactly two decimals. The first $ is a plain dollar sign; only $ followed by { starts an insertion.
Template literals can also span lines, which is handy for multi-line messages:
const report = `Pocket summary
Spent: $22.00
Left: $3.00`;
console.log(report);Characters, positions and slices
A string is a sequence of characters, and each one has a position called an index, counting from 0. length tells you how many characters there are.
const word = "Coffee";
console.log(word.length); // 6
console.log(word[0]); // first character
console.log(word.at(-1)); // last character
console.log(word.slice(0, 3)); // from index 0 up to, not including, 3
console.log(word.slice(3)); // from index 3 to the endword.at(-1) counts from the end, which saves you writing word[word.length - 1].
Methods that return new strings
Strings come with built-in methods, functions you call with a dot. The ones you will use weekly:
const raw = " Coffee with Sam ";
const clean = raw.trim();
console.log(clean); // spaces removed from both ends
console.log(clean.toUpperCase());
console.log(clean.includes("Sam")); // true or false
console.log(clean.startsWith("Coffee"));
console.log(clean.replaceAll(" ", "-"));
console.log("7".padStart(3, "0")); // "007"
console.log(`[${raw}]`); // the original is untouchedThat last line is the key idea: strings are immutable. No method ever changes a string; each one returns a new string. If you want to keep the result, store it.
Combining methods is common. To capitalise the first letter of a label, take the first character, uppercase it, and add the rest:
const label = "groceries";
const nice = label[0].toUpperCase() + label.slice(1);
console.log(nice);Two more methods answer “where is it?” rather than “is it there?”. indexOf("Sam") returns the index where the text first appears, or -1 when it is not there at all. And split(" ") cuts a string into pieces wherever it finds the separator and gives you back a list, ["Coffee", "with", "Sam"]. Lists are called arrays, and they get a whole lesson in section 3.
Strings and numbers, back and forth
Pocket constantly crosses the border between text and numbers. Amounts are numbers while you calculate and strings when you display them; typed input is a string until you convert it.
const cents = 450;
console.log(String(cents), typeof String(cents)); // number to string
console.log(`${cents}`.length); // a template literal converts too
console.log(Number("4.50") * 100); // string to number
console.log(Number(" 12 ")); // spaces around digits are ignored
console.log(Number("")); // careful: an empty string becomes 0The last line is a trap worth remembering. An empty text box converts to 0, not NaN, so “the user typed nothing” looks exactly like “the user typed zero”. When you validate forms in section 4, you will check for empty input before converting.
Comparing strings
=== compares strings character by character, and it is case-sensitive: "Food" === "food" is false. Users type categories however they like, so normalise before you compare: trim the spaces and pick one case.
const typed = " Food ";
console.log(typed === "food"); // false
console.log(typed.trim().toLowerCase() === "food"); // trueYou can also use < and > on strings. They compare character codes one position at a time, which works for simple lowercase words ("apple" < "banana" is true) and goes wrong quickly beyond that: "Zebra" < "apple" is also true, because every uppercase letter has a smaller code than every lowercase one. Section 3 shows the right way to sort text, with localeCompare, which follows the rules of a real language.
Pocket can now hold amounts, calculate with them exactly and print them in a form people can read. What it cannot do yet is react: warn you when you go over budget, or treat food differently from rent. In the next section your program starts making decisions.
Key takeaways
- Strings can use single quotes, double quotes or backticks; backticks make template literals, which can insert values with
${}and span several lines. - Strings are immutable, so methods like
trim()andtoUpperCase()return a new string and leave the original unchanged. - Characters are numbered from 0,
lengthcounts them, andslice(start, end)copies a piece up to, but not including,end. - Format cents for display with
(cents / 100).toFixed(2)orIntl.NumberFormat, and keep the stored amount as a number.