Booleans, null and undefined
Three small types carry the yes-or-no answers and the two different kinds of nothing that your programs will need constantly.
A boolean is true or false and usually comes from a comparison. undefined is absence the language produced; null is absence you chose. typeof null reports object, which is a famous and permanent bug.
EXERCISE
1Booleans Are Answers to Yes or No Questions
A boolean has exactly two possible values, and you will rarely type them by hand because comparisons produce them for you.
true and false. That is the entire type. You will write them literally now and then, but most booleans in real code are produced by a comparison.
Written by hand:
const isLoggedIn = true;
const hasPaid = false;
console.log(typeof isLoggedIn); // boolean
Produced by a comparison, which is far more common:
const age = 20;
console.log(age > 18); // true
console.log(age === 18); // false
console.log(age !== 18); // true
const isAdult = age >= 18; // store the answer
console.log(isAdult); // true
And produced by methods that ask a question:
const email = "ada@example.com";
console.log(email.includes("@")); // true
console.log(email.startsWith("ada")); // true
console.log(email.endsWith(".org")); // false
const looksValid = email.includes("@") && email.length > 5;
console.log(looksValid); // true
Pro Tip: Name booleans as questions.
isAdult,hasPaid,canEditandshouldRetryall read correctly at the point where they are used, becauseif (isAdult)is an English sentence. A boolean calledstatusorflagforces the reader to go and look up what true means.
EXERCISE
2Two Different Kinds of Nothing
undefined arrives when nobody supplied a value, and null arrives when somebody deliberately supplied emptiness.
The difference is about who decided.
undefined: the language had nothing to give you:
let prize;
console.log(prize); // undefined declared, never assigned
const user = { name: "Ada" };
console.log(user.age); // undefined no such property
function noReturn() {}
console.log(noReturn()); // undefined nothing came back
function greet(name) {
console.log(name);
}
greet(); // undefined argument not supplied
Four different routes, one meaning: nobody put a value here.
null: you put emptiness here on purpose:
let currentUser = null; // nobody is logged in, and I mean that
function logIn(user) {
currentUser = user;
}
function logOut() {
currentUser = null; // clearing it is meaningful
}
console.log(currentUser); // null
logIn({ name: "Ada" });
console.log(currentUser); // { name: 'Ada' }
Comparing them:
console.log(null == undefined); // true loose: both mean "empty"
console.log(null === undefined); // false strict: different types
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" the 1995 bug
console.log(null === null); // true this is how you check for null
Pro Tip: As a rule you never assign
undefinedyourself, because the language already uses it to mean "missing". When your code needs to say "empty on purpose", reach fornull. That way the two values stay meaningfully different and a strayundefinedis always a signal that something did not get supplied.
EXERCISE
3Converting Anything to a Boolean
Every value in JavaScript can be treated as true or false, and the short list of false ones is worth memorising today.
When a value is used where a yes-or-no answer is needed, converts it. There are exactly six falsy values, and everything else is truthy.
The complete falsy list:
console.log(Boolean(false)); // false
console.log(Boolean(0)); // false
console.log(Boolean("")); // false empty string
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
// That is all six. Memorise this list and you are done.
Everything else is truthy, including some surprises:
console.log(Boolean("0")); // true a string with a character in it
console.log(Boolean("false")); // true still just text
console.log(Boolean([])); // true an empty array is an object
console.log(Boolean({})); // true an empty object too
console.log(Boolean(-1)); // true only zero is falsy
console.log(Boolean(" ")); // true a space is a character
Why it matters in practice:
const name = "";
if (name) {
console.log("Got a name");
} else {
console.log("No name given"); // this one runs
}
// Careful with zero, which is a real value AND falsy:
const stock = 0;
if (stock) {
console.log("In stock");
} else {
console.log("Out of stock"); // correct here, but...
}
// ...if 0 were a valid reading, test explicitly:
if (stock !== undefined) {
console.log(`Stock level: ${stock}`); // Stock level: 0
}
Pro Tip: The two that catch people are the empty array and the number zero.
[]is truthy, soif (list)is true even when the list is empty and you almost always wantedif (list.length). And0is falsy, so any check on a count, a price or a score can silently treat a real zero as missing data.
