null is the value that means "there is no value"

Q: What is the sound of one hand clapping?

A: null

Null is useful

Null is used in cases where "nothing yet" is a valid scenario.

For instance, if a user has an account, but doesn't (yet) have a profile picture, account.profilePic may be null.

Then you can test for that case, e.g.

if (account.profilePic === null) {
} else {

Null is dangerous

let fruit = null

Please watch the instructor type this (or type it yourself) and then...

Read the error!

Errors are good

They tell you

Please try to interpret this error:

TypeError: Cannot read property 'toUpperCase' of null

TypeError explained

TypeError: Cannot read property 'toUpperCase' of null

This error is confusing because it buries the lede -- you must read all the way to the end before you find the relevant clue ("null"), and it omits the name of the variable whose value was null ("fruit").

Sadly, it is your job as a programmer to translate "TypeError: Cannot read property 'toUpperCase' of null" into "We expected the variable fruit to contain a string, but it contained null instead."

null pointer errors

If You're Going To Fail...

Two failure recovery philosophies:

Which idea is better?

Why or why not?

failure recovery: different modes for different roles

graceful - generally good for users

<<<<<<< variant A * provide information and context in non-technical language

variant B

fail-fast - generally good for coders

JavaScript has several nulls

Docs: MDN: null

This proliferation of nulls is generally a bad idea in language design, but JavaScript is stuck with them.

Nulls are falsy

All of the nulls in the previous slide are falsy, so they will cause an if statement to fall through. This allows the code from the earlier example to be written concisely:

if (user.profilePic) {
} else {

If user.profilePic is either null or undefined (or false or NaN or '') then we will show the default picture, thus avoiding a null pointer error when trying to show user.profilePic.

The pattern of checking for a valid value before proceeding is sometimes called a guard clause or defensive programming.

 Previous Lesson Next Lesson