JavaScript Basics: How Loops and Conditionals Handle Truthy and Falsy Values
Have you just started learning to code and used an "if condition" to make decisions based on an expression? If so, you have probably used Arithmetic Operators, Comparison Operators, or Logical Operators, among others.
When I started learning to code, I didn't know how an expression inside an "if" block was evaluated. I understood that if the condition was true, the code would enter the "if" block, and if it was false, it would skip it.
However, I didn't realize that expressions are evaluated to a Boolean value, and based on that Boolean value, we proceed further.
For a long time, I couldn't understand how a simple if condition worked because I didn't know about truthy and falsy values or how expressions are resolved to truthy and falsy.
So, let me now explain with code what I mean.
let firstName = ""
function getName(name){
if(name) // name is evaluated to falsy value as firstName is an empty string
{
console.log(name)
}
else{
console.log("this line will be logged onto console")
}
}
getName(firstName) // output : this line will be logged onto console
Below are a few more examples of truthy and falsy values in JavaScript.
Falsy Values
There are only a few values in JavaScript that are considered falsy:
false
0
-0
0n
(BigInt zero)""
(empty string)null
undefined
NaN
(Not-a-Number)
Examples
Falsy Values
if (!false) {
console.log("false is falsy");
}
if (!0) {
console.log("0 is falsy");
}
if (!"") {
console.log("empty string is falsy");
}
if (!null) {
console.log("null is falsy");
}
if (!undefined) {
console.log("undefined is falsy");
}
if (!NaN) {
console.log("NaN is falsy");
}
Output:
false is falsy
0 is falsy
empty string is falsy
null is falsy
undefined is falsy
NaN is falsy
Truthy Values
All values that are not falsy are considered truthy. This includes:
true
Non-zero numbers (e.g.,
1
,-1
,3.14
, etc.)Non-empty strings (e.g.,
"hello"
,"0"
,"false"
, etc.)Objects (e.g.,
{}
,[]
)Arrays (even empty arrays
[]
)Functions
Dates
Any other value that is not explicitly falsyTruthy Values
Examples
Truthy Values
if (true) {
console.log("true is truthy");
}
if (1) {
console.log("1 is truthy");
}
if ("hello") {
console.log("non-empty string is truthy");
}
if ({}) {
console.log("empty object is truthy");
}
if ([]) {
console.log("empty array is truthy");
}
if (function() {}) {
console.log("function is truthy");
}
Output:
true is truthy
1 is truthy
non-empty string is truthy
empty object is truthy
empty array is truthy
function is truthy
Thank you! If you find any errors, please comment below. I will be happy to correct them. Also, feel free to connect with me on LinkedIn.
Subscribe to my newsletter
Read articles from manish bhardwaj directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by