Unit 4 · Thinking like a programmer
"true" vs true: strings vs booleans
Booleans are written without quotes: true and false. "false" in quotes is a string, and any non-empty string counts as true in an if, so if ("false") runs.
The mix-up
What people often think
“"false" is a boolean.”
What the tutor says
Booleans are written without quotes. "false" is five letters of text, and code treats it as text.
How it works
The same goes for empty values. "" is still a string, just one with no letters. null means there is no value at all. They behave differently, so pick the one you mean.
When a function should answer yes or no, return the boolean itself, for example return n % 2 === 0, rather than the text "true".
Side by side
function isEven(n) {
if (n % 2 === 0) return "true";
return "false";
}
if (isEven(3)) { ... } // runs: "false" is truthyfunction isEven(n) {
return n % 2 === 0;
}Close cousins of this mix-up
The tutor watches for these in the same lesson.
“Empty quotes mean no value, so "" is null.”
"" is still a string, just one with no letters in it. null means there is no value at all.
“Returning "true" in quotes is a yes.”
"true" in quotes is text, not a boolean. Return true or false without quotes, or return n % 2 === 0.
Practise it with a tutor watching
Types: text, numbers and yes/no
Tell strings, numbers, booleans and null apart, and convert text to numbers on purpose.
Free with an account. The first two units need no account.