Borislav Hadzhiev
Mon Oct 18 2021·2 min read
Photo by J Scott Rakozy
Use the logical NOT (!) operator to check if a value is falsy, e.g.
if (!myValue)
. The logical NOT operator returns true
when it precedes falsy
values, in all other cases it returns false
.
const myVar = 0; if (!myVar) { console.log('✅ myVar is falsy'); } else { console.log('⛔️ myVar is truthy'); }
We use the
logical NOT (!)
operator to check if the myVar
variable stores a falsy value.
The falsy values in JavaScript are: false
, 0
, -0
, empty string, null
,
undefined
, NaN
.
Our if
block would run only if the value stored in the myVar
variable is one
of these values.
Here are examples of using the logical NOT (!) operator with falsy values:
console.log(!false); // 👉️ true console.log(!0); // 👉️ true console.log(!''); // 👉️ true console.log(!null); // 👉️ true console.log(!undefined); // 👉️ true console.log(!NaN); // 👉️ true
All other values are considered truthy.
if (![]) { console.log("⛔️ This doesn't run"); } else { console.log('✅ This runs'); } if (!{}) { console.log("⛔️ This doesn't run"); } else { console.log('✅ This runs'); }
Even though the array and object are empty, they are not one of the falsy values, as opposed to the empty string.
if (!"") { console.log('✅ This runs'); } else { console.log("⛔️ This doesn't run"); }
If you need to check if an array or object contains elements or key-value pairs, do this instead:
if (['a'].length > 0) { // 👉️ array is not empty } if (Object.keys({a: 'b'}).length > 0) { // 👉️ object is not empty }
In the example, we basically check if the array contains at least 1 element and the object at least 1 key-value pair.
You could also do the check implicitly, e.g.:
if ([].length) { // 👉️ if this runs, the array is not empty }
In this example, we access the length
property on an empty array, which
evaluates to 0
. Because 0
is a falsy value, the if
block doesn't run.