Madeline Zenz Logo

Truthy and Falsy


Truthy and falsy values just means that a value evaluates to true or false. They can be used in if statement or a while loop and, depending on if it is truthy or falsy, determine if the code is to run. If it is truthy (evaluates to true) the code will run, and if it is falsy (evaluates to false) the code will not run.
Some values that are falsy:

  • False
  • 0
  • "" (an empty string)
  • null
  • undefined

There are a few more but besides the few falsy values, all others will evaluate to true.

Example 1

In this example, we are testing to see if our variable x is falsy. If it evaluates to false then then we will see “True” in the console. If it evaluate to true then we will see “False” in the console. Our variable x is initialized to 0. 0 is a falsy value so the statement that it evaluates to false is true. We will see “True” in the console.

                x = 0
                if(x == false){

Example 2

Another example of using truthy/falsy values is to check to see if a variable has been initialized. We have not initialized the variable y. The if statement checks to see if the variable has been initialized. An uninitialized variable will evaluate to false. In this case, we will see “y has not been initialized” in the console.

                    console.log("y has been initialized to " y);
                    console.log("y has not been initialized");

If we were to initialize the variable y and then run this code, we would then see “y has been initialized to " and then the value it has been initialized to.