Falsy Values and Default Values
When JavaScript needs a boolean, it can use any value in its place. Some values then count as false. They are called falsy. There are exactly six of them: false, 0, "" (empty text), null, undefined and NaN. Every other value is truthy, which means it counts as true. That includes the strings "0" and "false", and also empty lists and objects, which you will meet later.
Boolean(x) shows whether a value is truthy or falsy:
console.log(Boolean(0));
console.log(Boolean(""));
console.log(Boolean(null));
console.log(Boolean("0"));
console.log(Boolean("hello"));
console.log(Boolean(-5));
Output:
false
false
false
true
true
true
"0" is a string with one character in it, so it is truthy. Only the number 0 is falsy.
Default values with ||
|| does not always give true or false. It gives back one of its two values. If the left value is truthy, || gives the left value. If it is falsy, || gives the right value. This makes || a quick way to set a default (a value to use when nothing useful was given):
const name = "";
console.log(name || "guest");
const city = "Lisbon";
console.log(city || "unknown");
Output:
guest
Lisbon
name is empty, which is falsy, so you get "guest". city is truthy, so you get "Lisbon".
When 0 is a real value, use ??
|| replaces every falsy value, and sometimes that is wrong. A count of 0 or an empty string can be a real value that you want to keep. For this, use ??. It is called nullish coalescing, and it uses the default only when the left value is null or undefined:
const count = 0;
console.log(count || 10);
console.log(count ?? 10);
const bonus = null;
console.log(bonus ?? 10);
Output:
10
0
10
count || 10 threw away the real 0 and gave 10. count ?? 10 kept the 0, because 0 is not null or undefined. For bonus, which is null, ?? used the default.
So the two operators answer different questions. || asks "is this value usable?" ?? asks "was a value given at all?" Use || when empty values should get the default, like a missing username. Use ?? when 0 or "" are real answers, like a count. A related operator, ?., comes in the Objects section.
In the exercise, read a score and give it a default with both || and ??, and see what each one does with 0.