In the last few lessons, you’ve been getting the day trip sign-up form ready for real visitors. You guarded cardNumber.length with cardNumber !== null && so a skipped answer couldn’t crash card.js, and you cleaned a typed membership answer with trim() and toLowerCase() before comparing it.
The form also asks each visitor for their age, and the ticket checker at the end of this course has to use that answer to price a ticket. A typed age arrives as text, though, and it can be missing, blank, or not a number at all. In this lesson, you’ll learn how JavaScript treats values that aren’t true or false in a condition, how to pick a fallback that keeps a real 0, and how to check an answer in a safe order before you use it.
Warm Up by Turning Text Into a Number
In an earlier course, you used Number() to turn numeric text into a number and Number.isNaN() to spot text that didn’t convert. Start the Node REPL by running node, and predict each result before you press Enter:
> Number("12")
12
> Number(" 7 ")
7
> Number("twelve")
NaN
> Number.isNaN(Number("twelve"))
true
> Number("")
0
> Number(" ")
0
Number() even ignores the spaces around " 7 ". The last two are the surprise. An empty or all-space answer becomes 0, not NaN, so a visitor who left the age box blank would quietly turn into a zero-year-old. That’s why the checks later in this lesson look for a blank answer before converting it.
Sort Values Into Truthy and Falsy
So far, every if condition you wrote gave true or false. JavaScript also accepts any other value as a condition. It treats a handful of values as if they were false, and these are called falsy values:
There’s one more, 0n, which belongs to a kind of number this course doesn’t use. Every other value is truthy, which means a condition treats it as true. To see how JavaScript classifies a value, pass it to Boolean(). Predict each line first:
> Boolean(0)
false
> Boolean("0")
true
> Boolean(" ")
true
> Boolean("false")
true
> Boolean(NaN)
false
> Boolean(-5)
true
The surprises are all strings. "0", " ", and "false" each contain at least one character, so they’re truthy. Only the empty string "" is falsy.
You’ll also see !!value in other people’s code. This expression does the same job as Boolean(value). The first ! flips the value to the opposite Boolean, and the second flips it back.
Now try a value directly in an if. Leave the REPL with .exit, then create nickname.js:
nickname.js
const nickname = "";
if (nickname) {
console.log(`Welcome, ${nickname}!`);
} else {
console.log("Welcome, traveler!");
}
Run it: