array.indexOf() starts testing at the specified point and then continues to move forward until it finds an element in the array that matches the specified value. Therefore, when you use [1,2,3].indexOf(2,undefined) , it starts with an array element with index 0 (which undefined converted to) and continues to check each element:
2 == 1 // false 2 == 2 // true, returns index 1
array.lastIndexOf() , however, begins to test back from the specified point. Therefore, when you use [1,2,3].lastIndexOf(2,undefined) , Javascript starts with an array element with index 0, then tries to continue backward:
2 == 1 // false, no more elements to test, return -1
source share