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
Example Program
let team = "CSK";
if (team) {
console.log("Team exists");
}
Output
Team exists
- 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
Example Program
let score = 0;
if (score) {
console.log("Pass");
} else {
console.log("No score");
}
Output
No score
- 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");
}
Output
Enter your name
- 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)