DEV Community

Cover image for Truthy and Falsy Values in JavaScript
Kavitha
Kavitha

Posted on

Truthy and Falsy Values in JavaScript

Truthy and Falsy Values in JavaScript

  • In JavaScript, values used inside a condition are automatically converted into either true or false.
  • This concept is called Truthy and Falsy values.
  • It is very important in conditional statements like if, else, and while.

What are Truthy Values?

  • A truthy value is any value that JavaScript treats as true when used inside a condition. Examples of Truthy Values
1
-10
"Hello"
"CSK"
[]
{}
true
Enter fullscreen mode Exit fullscreen mode

Example Program

let team = "CSK";

if (team) {
    console.log("Team exists");
}
Enter fullscreen mode Exit fullscreen mode

Output

Team exists
Enter fullscreen mode Exit fullscreen mode
  • Since "CSK" is a non-empty string, JavaScript treats it as true.

What are Falsy Values?

  • A falsy value is any value that JavaScript treats as false in a condition.

Falsy Values in JavaScript

  • There are only a few falsy values:
false
0
""
null
undefined
NaN
Enter fullscreen mode Exit fullscreen mode

Example Program

let score = 0;

if (score) {
    console.log("Pass");
} else {
    console.log("No score");
}
Enter fullscreen mode Exit fullscreen mode

Output

No score

Enter fullscreen mode Exit fullscreen mode
  • Since 0 is a falsy value, the else block runs.

Simple Example

let name = "";

if (name) {
    console.log("Welcome");
} else {
    console.log("Enter your name");
}
Enter fullscreen mode Exit fullscreen mode

Output

Enter your name
Enter fullscreen mode Exit fullscreen mode
  • Because an empty string "" is falsy, JavaScript executes the else block.

Why is it Important?

Truthy and falsy values help in:

  • checking empty input fields
  • validating forms
  • checking login details
  • making decisions in programs

Conclusion
Truthy and falsy values are the foundation of decision making in JavaScript.

Top comments (0)