Loading
0x30Lesson 4 of 16

Strings, errors and debugging

Transform text and use the console to find a wrong assumption.

17 min 2-question quiz 1 code exercise
By the end of this lesson you can
  • Use string methods and template strings
  • Trace a program with console.log and read an error
  • Catch a recoverable error without hiding a bug

Web apps clean user input constantly: trim whitespace, compare a normalized value, and show a friendly message. String methods return new strings; they do not modify the original. A template string uses backticks and ${value} to combine text and data.

normalize.js
1const raw = "  Ada  ";
2const name = raw.trim().toLowerCase();
3console.log(name);
4console.log(raw.length);
Output
ada
7

When code fails, read the first useful error and the line it points to. Ask: What did I expect this value to be? Use console.log or a debugger breakpoint to inspect it. Do not wrap every line in try/catch: handle only errors you can explain and recover from.

safe-json.js
1function readName(text) {
2  try {
3    return JSON.parse(text).name ?? "friend";
4  } catch {
5    return "friend";
6  }
7}
8console.log(readName(JSON.stringify({ name: "Ada" })));
9console.log(readName("broken"));
Output
Ada
friend

Key takeaways

  • String methods such as trim and toLowerCase return new values.

  • Inspect actual values and error locations when a program surprises you.

  • Catch expected failures such as invalid JSON; do not silently swallow unknown problems.

Lesson quiz

2 questions · pass with 2 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write JavaScript

Write the program, run it against the test cases, and use the feedback to build your JavaScript skills.

Exercise 1

Clean a sign-up name

+25 XP

Trim the input. If it is empty, print Name required. Otherwise print Welcome, NAME! with the first letter uppercase and the remaining letters lowercase.

  • Mixed case
  • Empty
main.js
Loading editor…

JavaScript runs in a sandboxed browser frame with a 1.5 second time limit. Input is available as the string variable input.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…