Hello, all!!! Hope you guys are safe. Today I'll talk about some tricky parts of JavaScript which you should definitely know to increase your knowledge in JS.
Truthy & Falsy Values
Let's start with the easy one. Sometimes you may write conditions where you would need to define if a variable is true theb it might do something and if it is false it might do something else. Here's an example
const age=4
if(age>0){
console.log('True')
}
else{
console.log('False')
}
Here you declared a variable called age and gave a condition that if age>0
then it will print True
otherwise it will print False
. Pretty straight right? Even if you don't write age
instead of age>0
it will still print True
(Try yourself in a IDE). It's happening because as variable age has a value other than 0 ,assigned to it it will always return True
. So 0 here is called a Falsy
value in JS.
So can you guess what should happen if I create a variable named name
and assign empty string
to it . What will be answer?
const name=''
if(name){
console.log('True')
}
else{
console.log('False')
}
If you ran the code you know the result. The answer is False
.So, you may already have a guess that JS basically treats any empty or null value as Falsy
values. So you might be asking what about empty arrays and objects? Both of them are Truthy
values because when you initiate an array or object without a property you are still creating a object. Objects are considered True
in JS. Array is also a type of Object.
Below here is a list of Truthy
and Falsy
values in JS. Please also check them by yourselves in your IDE.
Falsy Values
number = 0
string = "" (no white space)
undefined
null
NaN
False
Truthy Values
'0'
string = " " ( white space)
[] (empty array)
{} (empty object)
true
'false' (It's a string)
Top comments (0)