What Does the jQuery $.inArray() Method Check For?

The jQuery $.inArray() method checks whether a specific value exists within a JavaScript array. It searches through the array elements and returns the index of the first occurrence of the specified value. If the value is not present in the array, the method returns -1. This function acts as jQuery's cross-browser utility equivalent to native JavaScript's Array.prototype.indexOf().

Syntax and Parameters

The basic syntax for the method is:

$.inArray(value, array, [fromIndex])
  • value: The item you want to find within the array.
  • array: The array being searched.
  • fromIndex (optional): The index position in the array at which to begin the search. The default starting index is 0.

Strict Type Comparison

The $.inArray() method performs a strict comparison using JavaScript’s strict equality operator (===). This means both the value and the data type must match for the search to succeed.

For example, searching for the string "5" in an array containing only the number 5 will return -1 because their types differ:

var numbers = [1, 2, 5, 10];

$.inArray(5, numbers);   // Returns 2
$.inArray("5", numbers); // Returns -1

Handling the Return Value

Because arrays in JavaScript use zero-based indexing, the first element is located at index 0. In JavaScript conditional statements, 0 evaluates to false. Therefore, you should not check for the presence of an item using a simple truthy check:

// Incorrect approach:
if ($.inArray("apple", fruits)) {
    // This block fails if "apple" is at index 0
}

// Correct approach:
if ($.inArray("apple", fruits) !== -1) {
    // Executes correctly whenever "apple" exists in the array
}

Modern JavaScript Alternatives

In modern ECMAScript environments, native array methods are generally preferred over $.inArray(). You can use array.indexOf(value) for index retrieval or array.includes(value) if you only need a boolean (true or false) to confirm existence. However, $.inArray() remains useful for maintaining compatibility with legacy codebases relying on jQuery.