.padStart() and .padEnd()

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Padding the Start of a String

Suppose you are printing a battle scoreboard and want every score to line up in a neat column. Because `"7"`, `"42"`, and `"530"` do not have the same number of digits, the output looks uneven:

const scores = ["7", "42", "530"]; scores.forEach((score) => console.log("Score: " + score + " pts"));

The `.padStart(targetLength, padString)` method solves this by adding characters to the beginning of a string until it reaches the desired length: 1. `targetLength` is the total character length you want the final string to have. 2. `padString` is the character used to fill the missing space.

const scores = ["7", "42", "530"]; scores.forEach((score) => console.log("Score: " + score.padStart(3, "0") + " pts"));

Here, `"7"` becomes `"007"` and `"42"` becomes `"042"`, while `"530"` already has `3` characters so nothing is added. Now every line has the exact same width!

Exercise 2 — Padding the End of a String

The `.padEnd(targetLength, padString)` method works just like `.padStart()`, except it adds the filler characters to the end of the string instead of the beginning. This is ideal when displaying a list of Codémon names so that the status text after each name starts in the exact same column:

const team = ["Zap", "Aquachu", "Florachu"]; team.forEach((name) => console.log(name.padEnd(10, ".") + "ready"));

Every name is padded with dots until it is `10` characters long, so `"ready"` lines up cleanly on every row. - Use `.padStart()` to right-align numbers (like `"007"`). - Use `.padEnd()` to left-align words and names (like `"Zap......."`).

Exercise 3 — Default Spaces and Long Strings

If you leave out the second argument, both `.padStart()` and `.padEnd()` automatically fill the missing space with spaces (`" "`). We wrapped the results in `[` and `]` below so you can clearly see where the spaces are added:

console.log("[" + "Zap".padStart(8) + "]"); console.log("[" + "Zap".padEnd(8) + "]");

What if the string is already as long as (or longer than) the requested length? Nothing is added and nothing is cut off. Padding methods can only make a string longer—they never shorten it:

// "Florachu" already has 8 characters, so padStart(3, "0") changes nothing console.log("Florachu".padStart(3, "0")); console.log("Florachu".length);

Exercise 4 — Quiz: Padded How?

What does this code print?

console.log("5".padStart(3, "0"));
Options
• 005
• 500
• 5
• 000

Hint : The filler is added on the side the method name announces.

Exercise 5 — Quiz: Already Long Enough

What does this code print?

console.log("Aquachu".padStart(4, "*").length);
Options
• 7
• 4
• 11
• 3

Hint : Padding never removes characters.

Exercise 6 — Three-Digit Score

Display the score on three digits, filling with zeros.

Hint : Numbers are read from the right, and the filler is a character written as text.

Exercise 7 — Padding Numbers

Remember that `.padStart()` and `.padEnd()` are string methods—they do not exist on numbers! If you have a number like `const level = 7`, you must convert it to a string first with `String(level)` before calling `.padStart()`:

const level = 7; const formattedLevel = String(level).padStart(3, "0"); console.log(formattedLevel);

Combining `String()` and `.padStart()` is the standard way to format Codémon IDs, level counters, or timers so they always display a fixed number of digits:

const ids = [1, 23, 456]; ids.forEach((id) => { const code = "CDM-" + String(id).padStart(4, "0"); console.log(code); });

Exercise 8 — Aligned Names

Stretch each name to 10 characters so the levels line up.

Hint : Names read from the left, and the number is the total width you want.

Exercise 9 — Padding Cheat Sheet

Match each expression with its result.

Items to match
• "7".padStart(3, "0")
• "7".padEnd(3, "0")
• "Zap".padEnd(5)
• "Zap".padStart(2, "0")
Definitions
• "007"
• "700"
• "Zap "
• "Zap"

Exercise 10 — Aligned Scoreboard

Print the tournament scoreboard as a clean table where every column lines up perfectly.

Step 1: print the header line `"NAME SCORE"` exactly as shown. Step 2: for each fighter, print its name padded to 10 characters with spaces, followed by its score padded to 5 characters with zeros. Step 3: print a line of 15 dashes to close the table. Build it with `.padStart()` rather than typing the dashes by hand.

Expected output:

NAME SCORE Zap 00045 Aquachu 00600 Metachu 09512 ---------------
Starter code
const fighters = [ { name: "Zap", score: 45 }, { name: "Aquachu", score: 600 }, { name: "Metachu", score: 9512 } ]; // Write your code here
Back to the course