×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

Get index of an Array element in JavaScript

In this article, we will learn how to Get index of an Array element in JavaScript and return it to the program?
Submitted by Abhishek Pathak, on October 22, 2017

Arrays are an important data type in any language. Its property of storing elements together as one entity and ease of manipulating and performing operations on it makes it so popular to store data. Array stores the elements on the basis of index which is used to access and manipulate elements of the array.

Index of the array

The index of the array is the position of elements stored in the array. The tricky thing about the index is it begins with 0 and this confuses lots of new developers that are operating on array data type. The index ranges from 0 to length-1, where length is the length of the array, or simply the number of elements in the array. We can use this index to access the element. Here is a simple example of defining an array in JS and accessing its value.

Example

var array = [1, 2, 3, 4, 5];

console.log(array[0]); // Output: 1
console.log(array[1]); // Output: 2
console.log(array[4]); // Output: 5

//A tricky case
console.log(array[10]); //Output: undefined

Unlike C family, accessing the index greater than the length of the array is not error in JavaScript. We can access any index but since it is not defined, it will return undefined. Note that this doesn't affect the code if we don't require this element in any operation.

How to get index of an Array element in JavaScript?

To access any element, we have an in built property called, indexOf() which expects the input parameter that is the element itself that needs to be passed. Since we are checking the index of this element, so it requires the element from the array. If the element is found, it returns its position, otherwise, it will return -1. The reason being, if it returns 0, the 0 shall be the index of the array, which is wrong, since element is not present at any index, so it returns -1 value since, array doesn't have negative index.

Example to get index of an Array element

var array = [1, 2, 3, 4, 5];

console.log(array.indexOf(2)); //Output: 1
console.log(array.indexOf(50)); //Output: -1

Since the element 2 is at 1st index, so the first console statement returns output as the index of 2 which is 1. But 50 is not present in the array, so it returns -1. Using the in-built indexOf() method we can easily find the index of an element in an Array. indexOf can be also used to find substring of a string.

If you like this article, please share your thoughts in the comments below.

JavaScript Examples »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.