Lesson 4 of 28
In progress
Operators and strings
Do arithmetic and comparisons, build text with template literals, and slice, trim and split strings without guessing.
Strings are the type you touch most: names, labels, URLs, errors, everything a person types. A handful of methods covers almost all of it, and template literals remove most concatenation bugs.
What you will learn
- Use arithmetic, comparison and logical operators correctly.
- Build text with template literals and multi-line strings.
- Transform strings with methods that return new values.
Operators
Arithmetic: +, -, *, /, %, **. The remainder operator is useful for even checks and cycles; 7 % 2 is 1.
Assignment shortcuts: +=, -=, *=, /=. count++ increments by one and returns the old value in an expression, which is a source of off-by-one surprises. Prefer count += 1 on its own line.
Comparison: ===, !==, <, >, <=, >=. Strict equality is covered in the previous lesson.
Logical: &&, ||, !, plus ?? for nullish fallback.
Editable. Runs in your browser.
console.log(user.nickname || "Anonymous");
console.log(user.nickname ?? "Anonymous");
Press Run to see the output.
|| falls back for any falsy value, so an intentionally empty nickname becomes "Anonymous". ?? falls back only for null or undefined, which is usually what "missing" means.
&& and || short-circuit and return a value, not necessarily a boolean. a && b returns a if it is falsy, otherwise b. That is useful and easy to misread; use it for simple guards, not for clever chains.
Template literals
Backticks create strings that can span lines and interpolate expressions.
Editable. Runs in your browser.
const message = `Hello, ${name}.
Your score is ${score}, which is ${score >= 90 ? "excellent" : "good"}.`;
console.log(message);
Press Run to see the output.
Inside ${} you can put any expression: a variable, a calculation, a ternary, a function call. Keep expressions short; a template literal with a nested ternary is harder to read than a small helper function.
Multi-line strings need no n with backticks. That is why HTML templates and messages are easier to write this way.
The methods worth memorising
Editable. Runs in your browser.
console.log(raw.trim());
console.log(raw.trim().toLowerCase());
console.log("JavaScript".includes("Script"));
console.log("JavaScript".startsWith("Java"));
console.log("a,b,c".split(","));
console.log(["a", "b", "c"].join(" – "));
console.log("JavaScript".slice(0, 4));
console.log("JavaScript".replace("Java", "Type"));
Press Run to see the output.
Strings are immutable: every method returns a new string and leaves the original unchanged. raw.trim() does not modify raw, which is why you assign the result.
slice(start, end) excludes the end, like array slicing. substring is similar but swaps arguments when start is greater than end, which is rarely what you want. Prefer slice.
replace changes the first match. replaceAll changes every match, and neither changes the original.
Building a URL or a label
Template literals plus encodeURIComponent handle most cases.
Editable. Runs in your browser.
const name = " ana ";
const label = `Student: ${name.trim()}`;
console.log(label);
Press Run to see the output.
encodeURIComponent turns spaces and symbols into safe characters. Skipping it produces broken URLs as soon as someone searches for a & b.
Numbers and strings together
Anything from an input, a URL or localStorage is a string. Convert before arithmetic.
Editable. Runs in your browser.
const total = Number(price) * Number(quantity);
console.log(total.toFixed(2));
Press Run to see the output.
toFixed returns a string with fixed decimals, which is right for display and wrong for further calculation. Convert back with Number if you need to keep computing.
Common string tasks
- Initials:
name.split(" ").map(part => part[0]).join(""). - Title case: split, capitalise each part, join.
- Truncate:
text.length > 80 ? text.slice(0, 77) + "..." : text. - Slug: lowercase, trim, replace spaces with hyphens, strip punctuation.
Each is a small function rather than a chain copied into five places. That is the topic of module 2.
Comparing a number to a string with === is always false, so if (count === "0") silently never matches. Convert the string once at the boundary, or compare as strings deliberately, and keep the type consistent afterwards.
Given a full name with extra spaces, produce a label in the form "LAST, First" and a slug in the form "first-last". Log both, and log the number of characters in the trimmed name.
Show solution
Editable. Runs in your browser.
const first = parts[0];
const last = parts[parts.length – 1];
const label = `${last.toUpperCase()}, ${first}`;
const slug = parts.join("-").toLowerCase();
console.log(label);
console.log(slug);
console.log(input.trim().length);
Press Run to see the output.
split(/s+/) collapses repeated spaces, which split(" ") would turn into empty parts. join("-") then produces the slug without empty segments.
Recap
- Use
===, prefer??over||for missing values, and keep logical chains simple. - Template literals handle interpolation and multi-line text;
${}takes any expression. - String methods return new strings, so assign the result.
Next, you will read the console and the error messages it prints, which is the fastest debugging skill to acquire.
What is the difference between slice and splice?
Should I use double or single quotes?
Progress is saved in this browser only. No account, no email.