DEV Community

James L
James L

Posted on • Updated on

🎄JS Advent #1 - Truthy and Falsy values🎄

For the month of December I have challenged myself to write 24 articles about some JS concepts up until Xmas.

The first installment in this series is around Truthy and Falsy values in Javascript.

What is a Truthy or Falsy value?

A truthy value is any value in Javascript thatr returns true when converted to a Boolean and a falsy value is any value in Javascript which is false when converted to a Boolean.

For example, a non-empty string is a truthy value as it returns true when comverted with the double NOT, whereas an empty string evaluates to false so it is a falsy value.

!!"test" === true;
Enter fullscreen mode Exit fullscreen mode
!!"" === false;
Enter fullscreen mode Exit fullscreen mode

And a slightly confusing example, even if the string contains a falsy value it will return true:

console.log(!!"0") // true
console.log(!!"false") // true
Enter fullscreen mode Exit fullscreen mode

There are only a select few falsy values in Javascript. They are:

"", '', `` // empty strings
0 // zero (also minus 0)
null
NaN
false
undefined
Enter fullscreen mode Exit fullscreen mode
  • All other values in Javascript are truthy. Including empty arrays and objects.
The double NOT operator (!!)
  • The double NOT operator will convert the value to a Boolean context and return a boolean value as in the examples above but can also be confusing.

For example then using on a Boolean value initially:

console.log(!!true);
Enter fullscreen mode Exit fullscreen mode

This statement will negate true first to give us false and then negate false to give us true and then log that to the console.

So:

!!bVal === bVal

As an alternative you can also use the Boolean constructor:

const truthy = new Boolean("string");
console.log(truthy); // true
Enter fullscreen mode Exit fullscreen mode
const falsy = new Boolean(0);
console.log(falsy); // false
Enter fullscreen mode Exit fullscreen mode
AND and OR operators
  • You can also use the AND and OR operators with truthy and falsy values, as they will be converted upon evaluation.
!!({} && "") // returns false
Enter fullscreen mode Exit fullscreen mode
!!({} || "") // returns true
Enter fullscreen mode Exit fullscreen mode

JS Advent #2 >

Top comments (0)