Check if a Value is NOT in an Array using JavaScript

avatar

Borislav Hadzhiev

Sun Oct 31 20212 min read

banner

Photo by Yudi Susilo

Check if a Value is NOT in Array #

To check if a value is not in array array, use the logical NOT (!) operator to negate a call to the includes() method, e.g. !arr.includes(myVar). The expression will return true if the value is not included in the array and false otherwise.

index.js
const arr = ['a', 'b', 'c']; if (!arr.includes('z')) { console.log('โœ… value is not in array'); } else { console.log('โ›”๏ธ value is in array'); }

We used the logical NOT (!) operator to negate a call to the Array.includes method to check if a specific value is not contained in an array.

The includes method takes the value as a parameter and returns true if the value is contained in the array.

Since we want to check if the value is not contained in the array, we have to negate (!) the result.

Here are some 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.

Falsy values are: null, undefined, empty string, NaN, 0 and false.

The includes() method is not supported in Internet Explorer. If you have to support the browser, use the indexOf method instead.

An alternative approach is to use the Array.indexOf method.

Check if a Value is NOT in Array using indexOf #

To check if a value is not in array array, use the the indexOf() method, e.g. arr.indexOf(myVar) === -1. If the indexOf method returns -1, then the value is not contained in the array.

index.js
// Supported in IE const arr = ['a', 'b', 'c']; if (arr.indexOf('z') === -1) { console.log('โœ… value is not in array'); } else { console.log('โ›”๏ธ value is in array'); }
The indexOf method returns the index of the first occurrence of a value in an array, or -1 if the value is not contained in the array.

Our if statement checks if the method returned -1, if it did, we can conclude that the value is not in the array.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee