JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Array Search

8 April 2025 | Category:

In JavaScript, you can search through arrays to find values, check if an item exists, or get its position.

JavaScript provides multiple methods to help you search arrays easily and effectively.


✅ 1. indexOf() – Find the First Index

The indexOf() method returns the index of the first occurrence of a value.

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.indexOf("Banana")); // 1
console.log(fruits.indexOf("Orange")); // -1 (not found)

🔹 If the value is not found, it returns -1.


✅ 2. lastIndexOf() – Find the Last Index

The lastIndexOf() method returns the last occurrence of a value.

let nums = [1, 2, 3, 2, 4, 2];
console.log(nums.lastIndexOf(2)); // 5

✅ 3. includes() – Check if Value Exists

The includes() method checks whether a specific value is present in the array.

let colors = ["Red", "Green", "Blue"];

console.log(colors.includes("Green")); // true
console.log(colors.includes("Yellow")); // false

✅ 4. find() – Find First Matching Element

The find() method returns the first item that satisfies a condition (callback function).

let ages = [14, 18, 21, 16];

let adult = ages.find(age => age >= 18);

console.log(adult); // 18

🔹 It returns undefined if no match is found.


✅ 5. findIndex() – Find Index of First Match

Returns the index of the first element that satisfies a condition.

let nums = [5, 10, 15, 20];

let index = nums.findIndex(num => num > 10);
console.log(index); // 2

✅ 6. filter() – Find All Matching Elements

Returns a new array containing all elements that match a condition.

let scores = [80, 45, 90, 70, 50];

let passed = scores.filter(score => score >= 60);
console.log(passed); // [80, 90, 70]

📌 Quick Comparison Table

MethodReturnsUse Case
indexOf()Index (first match)Find position of a value
lastIndexOf()Index (last match)Find last occurrence
includes()true / falseCheck if value exists
find()First matching valueGet value based on condition
findIndex()Index of first matchGet index based on condition
filter()Array of matching valuesGet all values that match

🧠 Summary

  • Use indexOf() / lastIndexOf() for exact value searches.
  • Use includes() for simple existence checks.
  • Use find() and findIndex() when working with conditions.
  • Use filter() to get all values that match a condition.