Skip to contentPlayForge

What are truthy and falsy values in JavaScript?

Written by Jatin Thacker, Automation Architect · Updated

When a value is used as a yes or no, as in an if, JavaScript treats a short list of values as false: false, 0, -0, 0n, "", null, undefined and NaN. Everything else counts as true, including "0", [] and {}.

An if does not need a real true or false. Give it any value and JavaScript decides whether that value counts as true (truthy) or false (falsy). The falsy list is short enough to learn; everything not on it is truthy.

The example prints Boolean(value) for each sample. 0, '', null, undefined and NaN are falsy. The string '0', a price string like '₹0', an empty array [] and an empty object {} are all truthy. The last two surprise people: a check like if (rows) passes even when the list of rows is empty. Test the length instead, rows.length > 0.

The second half shows the bug that falsiness causes in test code. A quantity of 0 read from the page is a real value, but !qtyOnPage treats it as missing. When you mean "was a value provided?", say so: qtyOnPage == null is true only for null and undefined, so 0 is correctly reported as present.

Truthy checks are fine for genuine yes/no flags. For counts, prices and text from the page, compare against the value you actually mean.

truthy-falsy.mjs
const samples = [ ['0', 0], ["''", ''], ['null', null], ['undefined', undefined], ['NaN', NaN], ["'0'", '0'], ["'₹0'", '₹0'], ['[]', []], ['{}', {}], ]; for (const [label, value] of samples) { console.log(label.padEnd(9), Boolean(value)); } const qtyOnPage = 0; if (!qtyOnPage) { console.log('!qty says missing, but qty is', qtyOnPage); } if (qtyOnPage == null) { console.log('missing'); } else { console.log('== null says present:', qtyOnPage); }
Output
0         false
''        false
null      false
undefined false
NaN       false
'0'       true
'₹0'      true
[]        true
{}        true
!qty says missing, but qty is 0
== null says present: 0
Source:Falsy, Truthy
Test yourself
A helper returns an empty array when no orders match. Does if (orders) { ... } run its block?
Practise it(fix-052)

Try a real drill. No sign-up.

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.