how to check if value is truthy in javascript

In JavaScript, you can check if a value is truthy by using a simple conditional statement. Truthy values are those that evaluate to true in a boolean context. Here's how you can do it:

index.tsx
let value = 'hello'; // example truthy value
if (value) {
  console.log('The value is truthy');
} else {
  console.log('The value is falsy');
}
144 chars
7 lines

Alternatively, you can use the Boolean() function or the !! operator to explicitly convert a value to a boolean:

index.tsx
let value = 'hello'; // example truthy value
let isTruthy = Boolean(value); // or let isTruthy = !!value;
console.log(isTruthy); // outputs: true
146 chars
4 lines

Note that the following values are considered falsy in JavaScript:

  • false
  • 0
  • '' (empty string)
  • null
  • undefined
  • NaN (Not a Number)

All other values are considered truthy.

gistlibby LogSnag