DEV Community

loading...

Why does indexOf output like this?

programmerabhi profile image programmerabhi ・1 min read

var num = [26, 16, 41, 32, 16, 28, 16, 41];
console.log(num.indexOf(41));// 2
console.log(num.indexOf(41, 2)); // 2
console.log(num.indexOf(16, -1)); // -1 why?
console.log(num.indexOf(16, -2)); // 6

Discussion (2)

pic
Editor guide
Collapse
trolley33 profile image
Reece Trolley • Edited

Second argument to indexOf is the starting offset. Negative offsets start from the end of the array. Also if an element is not found -1 is returned. So if you start at the last element (-1th?) There is only 41 so 16 is not an element hence returning -1. If you start from the second to last element your search array is [16, 41] which does have 16 so it outputs the position in the overall array of that element (i.e. 6th position).

Collapse
mohsenalyafei profile image
Mohsen Alyafei • Edited
  1. Always remember that the search is always in a forward direction.

  2. The negative index tells where the starting position to search; it does not mean search backwards.

  3. You asked it to start searching from position -1 which is from the number 41 going forward. So there is nothing.