🎄JS Advent #1 - Truthy and Falsy values🎄
James L
Posted on December 1, 2022
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;
!!"" === false;
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
There are only a select few falsy values in Javascript. They are:
"", '', `` // empty strings
0 // zero (also minus 0)
null
NaN
false
undefined
- 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);
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
const falsy = new Boolean(0);
console.log(falsy); // false
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
!!({} || "") // returns true
Posted on December 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 27, 2024