Array Methods in JS - Part 2
JavaScript Array Search Methods What are Array Search Methods? Array Search Methods are used to: Find the position (index) of an element. Check whether an element exists. Retrieve an element that satisfies a condition. Find the index of an element that matches a condition. Search from the beginning or the end of an array. Common Array Search Methods Method Purpose Returns indexOf() Finds the first occurrence of a value Index or -1 lastIndexOf() Finds the last occurrence of a value Index or -1 includes() Checks whether a value exists true / false find() Finds the first matching element Element or undefined findIndex() Finds the index of the first matching element Index or -1 findLast() (ES2023) Finds the last matching element Element or undefined findLastIndex() (ES2023) Finds the last matching index Index or -1 1. Array.indexOf() Definition The indexOf() method searches an array for a specified value and returns the index of its first occurrence . If the value is not found, it returns -1 . Syntax array . indexOf ( searchElement ) array . indexOf ( searchElement , startIndex ) Parameters Parameter Description searchElement Value to search for startIndex (optional) Index where the search starts Returns Index of the first matching element. -1 if not found. Internal Working Suppose: let fruits = [ " Apple " , " Orange " , " Mango " , " Orange " ]; Memory: Index 0 → Apple 1 → Orange 2 → Mango 3 → Orange When: fruits . indexOf ( " Orange " ); JavaScript starts from index 0 : Apple ❌ Orange ✅ Found Stops immediately and returns: 1 Example let fruits = [ " Apple " , " Orange " , " Banana " ]; console . log ( fruits . indexOf ( " Orange " )); Output 1 Example - Not Found let fruits = [ " Apple " , " Orange " ]; console . log ( fruits . indexOf ( " Mango " )); Output -1 Example - Start Position let fruits = [ " Apple " , " Orange " , " Banana " , " Orange " ]; console . log ( fruits . indexOf ( " Orange " , 2 )); Output 3 Real-Time Example Suppose an e-commerce site wants to