DEV Community

programmerabhi
programmerabhi

Posted on

3

Why does indexOf output like this?

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

Top comments (2)

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay