Skip to content
the poor coder

check truthy or falsy javascript

Poor Man
Published
Reading time
1 min read
On this page

Check truthy or falsy JavaScript#

Truthy and falsy are terms used to describe the Boolean value of an expression. In JavaScript, every value can be evaluated as either truthy or falsy.

Truthy Values:#

  • Any non-empty string
  • Any number except 0 (including negative numbers and decimals)
  • true (boolean)
  • Any object
  • Arrays (even if empty)

Falsy Values:#

  • 0
  • null
  • undefined
  • false (boolean)
  • '' (empty string)

To check if a value is truthy or falsy, you can use a simple if statement:

Text
if (value) {
    // code to execute if value is truthy
} else {
    // code to execute if value is falsy
}

Note that the else block will be executed only if the value is falsy. If the value is truthy, the else block will be skipped.

You can also use the Boolean() function to convert a value to its Boolean equivalent (true or false):

Text
Boolean(value);

This will return true if the value is truthy and false if it's falsy.

Another way to check for truthy or falsy values is to use the double negation (!!) operator:

Text
!!value;

This will return true if the value is truthy and false if it's falsy. The double negation operator converts any value to its Boolean equivalent.

It's important to keep in mind that the truthiness or falsiness of a value depends on its context. For example, a string with only whitespace characters is considered truthy if it's not empty:

Text
if (' ') {
    console.log('This string is truthy');
} else {
    console.log('This string is falsy');
}

The above code will output "This string is truthy".

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC