How To Check If A Value Is NOT In An Array Using JavaScript

check if a value is not in an array using JavaScript

There are two general methods to check if a value is not in an array using JavaScript, being the .indexOf() and .includes() function of Array class or the .inArray() function of the JQuery class. Read the document for explanation.

Check if a value is not in an Array using JavaScript

Method 1: Using Array.indexOf(value)

The .indexOf() function simply returns the first index of a value in an array. If nothing is found, the function returns -1, which is what we’ll be checking for.

Syntax : Array.indexOf(value);

Parameters

NameTypeDescription
valuestring/intThe value to return the first occurrence index of.

Code

const arr = ["LMThong", "LearnShareIt"];

if (arr.indexOf("123") === -1)
    console.log("Value does not exist");

Console

"Value does not exist"

Method 2: Using Array.includes(value)

The .includes() function returns true/false depending on whether the value exists in the array. If nothing is found, the function returns false, which is what we’ll be checking for.

Though please note that the .include() function does not work on Internet Explorer while the .indexOf() function works on all browsers.

Syntax : Array.includes(value);

Parameters

NameTypeDescription
valuestring/intThe value to check if exists in array

Code

const arr = ["LMThong", "LearnShareIt"];

if (arr.includes("123"))
    console.log("Value does not exist");

Console

"Value does not exist"

Method 3: Using JQuery.inArray(value, array)

The .inArray() function is similar to the .includes() function in that they both only show whether a value is in an array, though instead of returning true/false it only returns 0/-1 (which represents true/false respectively). So in this case, we’re looking for -1, much like the .indexOf() method.

Please note that you need to check for either 0 or -1 specifically with ===, since 0 is technically false (falsy values) and -1 is technically true (truthy values) in terms of using ==.

Additionally, remember to download the JQuery script or here or copy this line into the <head>.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Syntax : JQuery.inArray(value, array);

Parameters

NameTypeDescription
valuestring/intThe value to check if exists in array
arrayarrayThe array to check in

Code

const arr = ["LMThong", "LearnShareIt"];

if (JQuery.inArray("123", arr) === -1)
    console.log("Value does not exist");

Summary

To check if a value is NOT in an array using JavaScript, you can either use the .indexOf() or the .includes() function. Both are viable options in this situation though .indexOf() looks for the index of a value instead of only checking existence. See also, the .lastIndexOf() function.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *