Truthiness, When Non-Booleans Act Like Booleans

Both languages let you use non-Boolean values where a Boolean is expected. Each value is then judged truthy or falsy.

The falsy values are almost identical in both languages: 0, empty string "", None/null, False/false, and empty collections in Python. Everything else is truthy.

Truthiness

PYTHON

print(bool(0))        # False
print(bool(""))       # False
print(bool([]))       # False, empty list
print(bool("Sankofa"))# True
print(bool(42))       # True

JAVASCRIPT

console.log(Boolean(0));         // false
console.log(Boolean(""));        // false
console.log(Boolean([]));        // TRUE, surprise!
console.log(Boolean("Sankofa")); // true
console.log(Boolean(42));        // true
Compare → Nearly identical, with one real trap. An empty list is FALSY in Python but an empty array is TRUTHY in JavaScript. This is a genuine language difference that catches experienced developers. In JavaScript, check arr.length === 0 instead.
EXAMPLE
loading editor…
YOUR TURN
Your turn → This is the default-value pattern, used constantly in real code. Set name to your own name and rerun, the backup disappears.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ Why truthiness earns its complexity

It lets you write display = name or "Friend" instead of a five-line check. Powerful, and exactly why you must know that 0 is falsy. If a user's score is 0, score or 100 quietly hands back 100. Knowing the falsy list is what separates a bug from a feature.

◈ Graded Challenge

Using the applicant variables, create merit (GPA 3.5 or above AND enrolled) and service (100 or more hours OR first generation). Mind your operators.

Name it exactly: merit, service

2 visible + 1 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back