Borislav Hadzhiev
Sun Oct 31 2021·2 min read
Photo by Yudi Susilo
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.
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.
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.
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.
true
, in all other cases it returns false
.Falsy values are: null
, undefined
, empty string, NaN
, 0
and false
.
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.
To check if a value is not in array array, use the indexOf()
method, e.g.
arr.indexOf(myVar) === -1
. If the indexOf
method returns -1
, then the
value is not contained in the array.
// 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'); }
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.