Mozilla documentation

Truthy

Falsy

Introduction

Truthy and falsy values are values that are considered true/false in a boolean context, but not actually a boolean.

Here are some well-known falsy values 0, "", null, undefined

Truthy values are anything that aren’t falsy 1, 2, "a", "asdf", { a: 'a' }

if (1)
	console.log('truthy') // will print "truthy" 
// checks if the array is empty
if (!array.length) console.log('empty array!') 

Usage with logical operators

When used with the logical AND operator &&, a truthy expression returns the last value and a falsy returns the first falsy value

1 && 'a' // returns 'a' since this evaluates to truthy
1 && 0 && 'a' // returns 0 since this evaluates to falsy

When used with the logical OR operator ||, a truthy expressions returns the first truthy value and a falsy returns the last value

1 || 'a' || 0 // returns 1 since this evaluates to truthy
undefined || '' || 0 // returns 0 since this evaluates to falsy

This technique is very useful when conditionally rendering components in React.js

const arr = []

render(
	<div>
		{ /* here we conditionally render the <p/> text if the array isn't empty */ }
		{arr.length && <p>array is not empty!</p>}
	</div>
)