mohan babu
mohan babu

Reputation: 1448

Trying to understand the functionality of array.IndexOf() in JavaScript

I understand that the array.indexOf() function gives you the index of a particular element in an Array.

If an Element is found, Array.indexOf() returns the position of that element in the array.

If the Element is not found, Array.indexOf() would return -1 as an output.

However, I am trying to understand the output in the following scenario.

var arr = [2,3,4,5,7,5];

for(var i =0;i<arr.length;i++) {
  console.log(arr.indexOf(i));
}

Output :

-1 -1 0 1 2 3

According to the Logic, When it finds 2 and 3 it should not return -1 in the console.

Going by the sequence of output i understand that the array index 0 starts at element 4 ?? Why is this happening?

I am just trying to understand what is going on?? Any Help would be highly appreciated.

Upvotes: 1

Views: 68

Answers (1)

MannfromReno
MannfromReno

Reputation: 1276

-1 means the value was not found in the target array. The 0 means that the value was found at position 0 in the array and so on.

So when i = 2 in the loop it is finding the value 2 at position 0 in arr.

For reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

Upvotes: 3

Related Questions