The Wayback Machine - https://web.archive.org/web/20240926162257/https://www.geeksforgeeks.org/javascript-array-indexof-method/
Open In App

JavaScript Array indexOf() Method

Last Updated : 12 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The JavaScript Array indexOf() method returns the position of the first occurrence of a value in a string. If the value is not found, it returns -1. This method provides a simple way to determine the position of specific characters or substrings within strings.

Syntax:

array.indexOf(element, start)

Parameters:

  • element: This parameter holds the element whose index will be returned.
  • start: This parameter is optional and holds the starting point of the array, where the default value is 0 to begin the search.

Return value:

This method returns the index of the first occurrence of the element. If the element cannot be found in the array, then this method returns -1.

Example 1: Finding Index of Element in Array

This code demonstrates the use of the indexOf() method to find the index of the element “gfg” in the array name. The index of “gfg” is stored in the variable a and then logged to the console.

JavaScript
let name = ['gfg', 'cse', 'geeks', 'portal'];
a = name.indexOf('gfg')
// Printing result of method
console.log(a)

Output
0

Example 2: Searching Element in Array

This code demonstrates the use of the indexOf() method to find the index of a specific element (2) in an array (A). It returns the index of the first occurrence of the element in the array (1 in this case). If the element is not found, it returns -1.

JavaScript
// Taking input as an array A
// having some elements.
let A = [1, 2, 3, 4, 5];

// indexOf() method is called to
// test whether the searching element
// is present in given array or not.
a = A.indexOf(2)

// Printing result of method.
console.log(a);

Output
1

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers:

JavaScript Array indexOf() Method- FAQs

How does the indexOf() method work?

The indexOf() method searches the array for the specified element, starting from the beginning. It uses strict equality (===) to compare elements and returns the index of the first occurrence of the element. If the element is not found, it returns -1.

How does indexOf() handle NaN values?

The indexOf() method uses strict equality (===) for comparison, which means it cannot find NaN values because NaN is not equal to NaN.

What happens if the fromIndex is out of bounds?

If fromIndex is greater than or equal to the array length, indexOf() returns -1. If fromIndex is negative, it is treated as array.length + fromIndex.

What is the performance of the indexOf() method?

The indexOf() method only finds the index of a specific element, while findIndex() can be used to find the index of an element that meets a certain condition defined by a function.

What are some common use cases for the indexOf() method?

Common use cases for the indexOf() method include:

  • Finding the position of a specific element in an array.
  • Checking if an element exists in an array by comparing the returned index to -1.
  • Implementing functionality that requires knowing the first occurrence of an element.

Previous Article
Next Article

Similar Reads

JavaScript indexOf() method in an Object Array
In JavaScript, indexOf() methods provide the first index at which the given element exists, and -1 in case it is not present in the array. Syntax: indexOf(element)indexOf(element, start);Parameters: element: the element to be searched in the input arraystart: the index from which the search has to begin. The default value is set to 0.Return value:
2 min read
JavaScript typedArray.indexOf() Method
The typedArray.indexOf() is an inbuilt function in JavaScript which is used to return the index of the element if found in the given typedArray otherwise it returns -1. Syntax: typedarray.indexOf(Element, Index); Parameters: It accepts two parameter which are specified below- Element: It is the element which are being searched for index in the type
2 min read
JavaScript String indexOf() Method
The JavaScript String indexOf() method finds the index of the first occurrence of the argument string in the given string. The value returned is 0-based. The indexOf() method is case-sensitive. Syntaxstr.indexOf(searchValue , index);ParameterssearchValue: The searchValue is the string to be searched in the base string. index: The index defines the
3 min read
How to make Array.indexOf() case insensitive in JavaScript ?
The task is to make the Array.indexOf() method case insensitive. Here are a few of the techniques discussed with the help of JavaScript. Table of Content Using JavaScript toLowerCase() Method Using JavaScript toUpperCase() Method: Using Array.findIndex() and RegExpUsing JavaScript toLowerCase() Method Transform the search string and elements of the
2 min read
TypeScript Array indexOf() Method
The Array.indexOf() method in TypeScript is used to find the index of the first occurrence of a specified element in an array. If the element is not found, it returns -1. Syntaxarray.indexOf(searchElement[, fromIndex])Parameter: This method accepts two parameters as mentioned above and described below: searchElement: This parameter is the Element t
2 min read
Node.js Buffer.indexOf() Method
Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like the array of integers. The Buffer.indexOf() method firstly checks for the input value, if it present in the buffer then it returns the first position (index) from where the value is starting. Syntax: buffer.indexOf( value, start,
2 min read
Ember.js MutableArray indexOf() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
4 min read
Ember.js EmberArray indexOf() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
3 min read
Ember.js ArrayProxy indexOf() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
3 min read
Ember.js Ember.NativeArray indexOf() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
4 min read
TypeScript String indexOf() Method
The indexOf() method in TypeScript is an inbuilt function used to find the index of the first occurrence of a specified value within a calling string. If the value is not found, it returns -1. Syntaxstring.indexOf(searchValue[, fromIndex]) Parameter: This method accepts two parameters as mentioned above and described below. searchValue: This parame
2 min read
Lodash _.indexOf() Method
lodash _.indexOf() method is used to get the index of the first occurrence of the particular element in the array. If fromIndex is absent in the array, a negative one is given as the output and no error is displayed. Syntax:indexOf(array, value, fromIndex);Note: If the value is not found in the array -1 is returned.Parameters:array: It is the array
2 min read
Difference Between indexOf and findIndex function of array
The task is to differentiate between the indexOf() and findIndex() methods of JavaScript. we're going to discuss both approaches. JavaScript indexOf() Method: This method is used to find the index of the first occurrence of the elements provided for search as the argument to the function. Syntax: arr.indexOf(element[, index]) Parameters: element: T
2 min read
Node.js indexOf() function
The indexOf() function is a string function from Node.js which is used to find a string with another string. Syntax: str1.indexOf( str2 ) Parameter: This function uses two parameters as mentioned above and described below: str1: It holds the string content where another string is to be searched.str2: It holds the search string. Return Value: The fu
1 min read
Underscore.js _.indexOf() Function
Underscore.js _.indexOf() gives the index of the element whose position we need to find. It starts to count the position of the elements in the array from 0. If the element is not present in the array then the result will be -1. Syntax: _.indexOf(array, value, [isSorted]);Parameters:array: It is the array, in which we want to find out the index of
3 min read
How to extend an existing array with another array without creating a new array in JavaScript ?
JavaScript arrays are a powerful data structure that allows you to store and manipulate collections of data. Often, we may need to combine or extend two or more arrays into a single array. It's easy to create a new array by concatenating two or more arrays but if we want to extend an existing array without creating a new array. There are two easy w
2 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How does Promise.all() method differs from Promise.allSettled() method in JavaScript ?
In this article, we will first understand in brief the Promise.all() as well as Promise.allSettled() methods and then we will try to visualize how they differ from each other through some theoretical as well as some coding examples. Both Promise.all() and Promise.allSettled() methods are the methods of a Promise object (which is further a JavaScrip
4 min read
How does Promise.any() method differs from Promise.race() method in JavaScript ?
In this article, we will first try to understand how we may declare or use Promise.any() and Promise.race() methods followed by some facts which will eventually help us to understand how they differ from each other (through theoretical as well as coding examples). Let us first quickly understand in brief about both the methods followed by their syn
5 min read
How toReversed() method is different from reverse() method in JavaScript
In JavaScript, reverse() and toReversed() methods do the same job as reversing but toReversed() does not change the original array. The reverse() method changes the original array. Below we have explained both methods. Table of Content Reverse() MethodtoReversed() methodReverse() MethodThe reverse() method is a built-in method for arrays in JavaScr
2 min read
Implement polyfill for Array.prototype.map() method in JavaScript
In this article, we will learn how to implement a polyfill for an Array.prototype.map() method in JavaScript. What is a polyfill? A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or because the new version of the br
3 min read
JavaScript Array map() Method
JavaScript Array map() Method method creates a new array with the results of a called function for every array element. This function calls the argument function once for each element of the given array in order. Syntax: // Arrow function map((element) => { /* … */ }) map((element, index) => { /* … */ }) map((element, index, array) => { /*
3 min read
JavaScript Array valueOf() Method
The JavaScript Array valueOf() method in JavaScript is used to return the array. It is a default method of the Array Object. This method returns all the items in the same array. It will not change the original content of the array. It does not contain any parameter values. Syntax: array.valueOf()Parameters: This method does not accept any parameter
2 min read
How to use Array.prototype.reduce() method in JavaScript ?
The Array.prototype.reduce() method is used in an array to return a single value from an array after executing the user-supplied callback function on each element of the array. It transverses from the left-most-element to the right-most-element of the given array. Array.prototype.reduce() can be called using two ways. Callback function: The functio
3 min read
Which one method use to delete an element from JavaScript array (slice or delete) ?
We can use both methods to delete an element from a javascript array. The answer is solely dependent on the application and on the programmer. What slice() method does? The slice method, as the name suggests, slices an array and returns a copy of the new array. This method does not affect the main array, it just returns the copy of the array. We ca
4 min read
Which built-in method removes the last element from an array and returns that element in JavaScript ?
In this article, we will know how to remove the last element from an array using the built-in method in Javascript, along with understanding its implementation through the examples. There are a few Javascript built-in methods and techniques with which we can remove the last element of the array. We will focus only on the 2 methods ie., the pop() me
3 min read
Implement polyfill for Array.prototype.reduce() method in JavaScript
In this article, we will learn how to implement a polyfill for an Array.prototype.reduce() method in JavaScript. A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or the new version of the browser does not have that
2 min read
JavaScript Array findLastIndex() Method
The Javascript findLastIndex() method is used to find the index of the last element in an array that matches the specified condition. It works by iterating over the array from the end to the beginning and returning the index of the first element that satisfies the condition specified in a callback function. If no element matches the condition, the
2 min read
How the Array.unshift() method works in JavaScript ?
The Array.unshift() method in JavaScript is used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array after the elements have been added. Key points about Array.unshift(): It modifies the original array and returns the new length.It can accept multiple arguments, and each a
1 min read
What is the use of the Array.from() method in JavaScript ?
In JavaScript, the Array.from() method is used to create a new array instance from an iterable object or array-like object. It provides a way to convert objects that are not inherently arrays into actual arrays. Example: Here we see that output creates a new array whose content is the same as input in the case of an integer. C/C++ Code console.log(
1 min read