In Javascript, every value has a data type and can be coerced or changed into a boolean value when need be.
Truthy values are always true and return true when used within a boolean context. Falsy values on the other hand are always false and return false when called within a boolean context.
Boolean contexts include conditionals, loops or comparison using loose equality "==" or strict equality "===".
There are 8 falsy values that are already defined by Javascript.
The 8 falsy values include:
false
0
(zero)-0
(-zero)' '
and" "
(empty string)null
undefined
NaN
(Not-a-Number)0n
(BigInt)
Every other value besides the above values is a truthy value. This includes the following values which may appear to be falsy values:
'0'
'false'
[]
(empty array){}
(empty object)function () {}
(empty function)
Converting(coercing) truthy and falsy values into proper booleans
At times you would like to know the boolean value of a given variable value in order to use it. In other scenarios, you would like to use a given value but as a boolean hence the need of converting the value into a boolean. There are two ways to do this: using double negation(!!) and using the boolean function.
The Double Negation (!!)
The double negation converts a value into a boolean value. The double negation converts the value into its corresponding boolean value. A falsy value will return false while a truthy value will return true.
!!null //false
!!undefined //false
!!1 //true
!!0 //false
!![] //true
The Boolean function (boolean())
The boolean function converts any value passed to it into a boolean value.
return boolean(0) //false
return boolean("faith") //true
return boolean("") //false
return boolean([]) //true
Truthy and falsy values can be used in conditionals and loops. The conditional or loop first evaluates whether the value is truthy or falsy then goes ahead to execute the command.
I hope this article helps you answer the question on the difference between truthy and falsy values in Javascript. Check out my earlier articles for more basic Javascript interview questions and answers.
If you liked the article remember to react and share for it to reach more people. I also love and appreciate feedback. Thanks for reading this far!