What are truthy and falsy Values in Javascript?

What are truthy and falsy Values in Javascript?

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:

  1. false
  2. 0 (zero)
  3. -0 (-zero)
  4. ' ' and " " (empty string)
  5. null
  6. undefined
  7. NaN(Not-a-Number)
  8. 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:

  1. '0'
  2. 'false'
  3. [] (empty array)
  4. {} (empty object)
  5. 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!