In JavaScript, truthy and falsy values determine how a value behaves in a conditional statement. Some values are automatically considered true, while others are automatically considered false. Knowing how JavaScript handles these values can save time and reduce errors in your code. Let's explore! π΅οΈββοΈ
π§ Example 1: Truthy and Falsy in Action
const useremail = "ayushyadavz@gmail.com";
if (useremail) {
console.log("Got user email");
} else {
console.log("Don't have user email");
}
// Output: Got user email
Explanation: Here, the string "ayushyadavz@gmail.com"
is considered truthy, which means the code inside the if
block is executed. If useremail
had a falsy value, the else
block would run instead.
π What are Falsy Values?
In JavaScript, the following values are falsy, meaning they are treated as false
in conditional statements:
false
0
-0
-
0n
(BigInt zero) null
undefined
-
NaN
(Not a Number)
π What are Truthy Values?
Anything not on the falsy list is truthy. This includes:
-
"0"
(string) -
'false'
(string) -
" "
(space character in a string) -
[]
(empty array) -
{}
(empty object) -
function() {}
(any function)
π Example 2: Checking for Empty Arrays & Objects
Sometimes, we need to verify if an array or object is empty. Let's see how to do that.
π Checking an Empty Array:
const username = [];
if (username.length === 0) {
console.log("Array is Empty");
}
// Output: Array is Empty
Explanation: Here, we use the .length
property to check if the array username
has any elements. If its length is 0
, it is considered empty.
𧳠Checking an Empty Object:
const useremailId = {};
if (Object.keys(useremailId).length === 0) {
console.log("Object is Empty");
}
// Output: Object is Empty
Explanation: In the case of an object, we use Object.keys()
to retrieve an array of the objectβs keys. If the array length is 0
, the object is empty.
π― Key Takeaways:
Falsy Values: These include
false
,0
,null
,undefined
,NaN
, and empty or "falsey" values that JavaScript treats asfalse
.Truthy Values: Everything else that has a value or type in JavaScript, like
"0"
,"false"
,[]
,{}
, or functions, are considered truthy.Empty Check: Use
.length
to check for empty arrays andObject.keys(obj).length
to check for empty objects.
Understanding truthy and falsy values helps you better control your conditional logic and write efficient, error-free code. Ready to level up your JavaScript skills? π
Top comments (2)
thank you
Thank you sir.