Truthy and Falsy Values in Javascript

  • Post category:Javascript
  • Reading time:2 mins read

Truthy values are those values that are considered true when encountered in a Boolean context. In Javascript, there are 5 falsy values and everything else are truthy values.

Now, let’s read more about the Truthy and Falsy Values in Javascript.

Truthy and Falsy Values in Javascript

These are the 5 Falsy Values in Javascript.

  1. 0 (zero)
  2. ” ” (Empty string)
  3. undefined
  4. null
  5. NaN

Truthy and Falsy Values in Javascript using Examples

console.log(Boolean(0));
console.log(Boolean(undefined));
console.log(Boolean("codeyup"));
console.log(Boolean({}));
console.log(Boolean(""));
console.log(Boolean(null));
console.log(Boolean(NaN));
Output:
false
false
true
true
false
false
false

Note: If the value is not an empty string then it will be a truthy value. For example “codeyup” is a truthy value because it is not an empty string.

let myNum = 0;
if (myNum) {
  console.log("Let's play the music");
}
else {
  console.log("music off");
}
Output: music off

Explanation:

In this code, I have taken 0 in myNum which is a falsy value. So, in this case, else block will execute and you can see the output in the console.

If I have taken any truthy value such as 1, 2, etc then If block will be executed in this scenario.

let place;
if (place) {
  console.log("Europe");
} else {
  console.log("Place is not defined. Please provide the place name");
}
Output: Place is not defined. Please provide the place name

Again, I have taken a falsy value. In this example, place variable is a falsy value because it is not defined yet. Undefined is falsy so the else block will run and execute the code written in the else statement.

Share this