Lesson 1 · Unit 06
Errors and missing values
Read a crash, catch it, and handle "nothing"
What you practise
- Reading a stack trace,
try,catch,finally,throw new Error,nullagainstundefined,?.and??
Try a question from this lesson
Pick one
A missing key gives undefined. Line 3 then asks that undefined for its length. How many lines does this program print?
const user = { name: "Ada" };
console.log(user.email);
console.log(user.email.length);
console.log("done");Correct answer
1
Why
Line 2 prints undefined. On line 3, undefined has no properties at all, so asking for one is an error: JavaScript throws a TypeError and the program stops right there. "done" is never printed.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Reading an error
When a program stops with an error, it tells you three things. Read from the top.
The line that failed, with a ^ under the exact spot. The error's name and message. Then the stack trace: the functions that were running, the most recent first, each with file:line:column.
Node adds more lines about its own insides below these. Ignore them.
/app/shop.js:2
return item.price * qty;
^
ReferenceError: qty is not defined
at cost (/app/shop.js:2:23)
at total (/app/shop.js:6:10)
at main (/app/shop.js:11:15)Concept
try, catch, finally
Code that might fail goes in a try block. If a line in it throws, the rest of the block is skipped and the catch block runs. It receives the error as an object with a name and a message.
A finally block runs afterwards, error or not. Then the program carries on instead of stopping.
const user = undefined;
try {
console.log(user.name); // throws
console.log("skipped");
} catch (err) {
console.log("caught a " + err.name);
} finally {
console.log("always runs");
}
console.log("still alive");Concept
null, ?. and ??
undefined is JavaScript saying "nothing was ever put here". null is a programmer saying "empty, on purpose". Asking either for a property throws.
a?.b reads b only when a is not null or undefined. Otherwise it quietly gives undefined.
a ?? b gives a, unless a is null or undefined: then it gives b.
const user = { name: "Ada", pet: null };
console.log(user.pet); // null
console.log(user.car); // undefined
console.log(user.pet?.name); // undefined
const pet = user.pet?.name ?? "no pet";
console.log(pet); // no pet9 more exercises in the app
- 3× multiple choice
- 3× type the answer
- 1× true or false
- 1× fill the blanks
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.