Check if Array Doesn't include a Value in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if Array Doesn't include a Value #

To check if an array doesn't include a value, use the logical NOT (!) operator to negate the call to the includes() method. The NOT (!) operator returns false when called on a true value and vice versa.

index.js
const arr = ['a', 'b', 'c']; const notIncludesD = !arr.includes('d'); console.log(notIncludesD); // 👉️ true const notIncludesC = !arr.includes('c'); console.log(notIncludesC); // 👉️ false if (notIncludesC) { console.log('✅ the value c is NOT included in the array'); } else { console.log('⛔️ the value c is included in the array'); }

We used the logical NOT (!) operator to negate the calls to the Array.includes method.

This approach allows us to check if a specific value is not contained in the array.

Our first example checks if the value d is not contained in the array and returns true.

index.js
const arr = ['a', 'b', 'c']; const notIncludesD = !arr.includes('d'); console.log(notIncludesD); // 👉️ true const notIncludesC = !arr.includes('c'); console.log(notIncludesC); // 👉️ false

The string c is contained in the array, so the expression returns false.

Here are some more examples of using the logical NOT (!) operator.

index.js
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true

You can imagine that the logical NOT (!) operator first converts the value to a boolean and then flips the value.

When you negate a falsy value, the operator returns true. In all other cases it returns false.

The falsy values in JavaScript are: null, undefined, empty string, NaN, 0 and false.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.