Truthy and Falsy

Every value can act as a condition

An if statement does not insist on being handed true or false. It takes whatever value you give it and asks one question: is this value truthy or falsy? A truthy value runs the block. A falsy value skips it.
So a bare number is a perfectly legal condition.

The falsy list is short enough to memorise

There are exactly six falsy values in the JavaScript you will write this year. Learn these six, and you know that every other value in the language is truthy.
Falsy valueWhat it usually means
falsethe boolean itself
0a count or a total of nothing
"" (the empty string)text with no characters in it
nulla slot deliberately left empty
undefineda slot that was never filled in
NaNarithmetic that did not produce a number

Boolean(x) asks the question out loud

If you want to see the verdict instead of acting on it, hand the value to Boolean. It gives back the same true or false that an if statement would have used.

and and or hand back an operand, not a verdict

This is where JavaScript parts company with most first languages. These two operators do not produce true or false. They pick one of the values you gave them and hand it straight back.
• The or operator scans left to right and returns the first truthy operand. If nothing is truthy, it returns the last one.
• The and operator scans left to right and returns the first falsy operand. If nothing is falsy, it returns the last one.
Either way the value that comes out is one of the operands you started with.

Why that is useful

Because or hands back an operand, it doubles as a way to supply a default value. Read the second line below as: use nickname, unless nickname is falsy, in which case use guest.
The program below asks for a team name and uses || to supply a default when nothing is typed. Run it and type a team name. Then run it again for each of these:
• Press Enter without typing anything.
• Type a single space, then press Enter.
• Change || to &&, and type a team name.
let entered = prompt("Team name: ");
let team = entered || "Unnamed team";
console.log("Typed something:", Boolean(entered));
console.log("Team:", team);
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.