indexOf()

noun

say it: “IN-deks OV” /ˈɪndɛks ʌv/

A JavaScript method that gives the position of the first matching item in an array, or of the first match in a string, counting from 0. It gives -1 when there's no match.

What is indexOf() in JavaScript?

indexOf() — An array (and string) method that gives the index of the first item equal to the value you pass, counting from 0, or -1 when it isn't there. Check for -1 before you use the answer.

const playlist = ['Highway Sunrise', 'Desert Radio', 'Windows Down'];
console.log(playlist.indexOf('Desert Radio'));  // 1
console.log(playlist.indexOf('Mile Marker 9')); // -1

In a sentence

  • “playlist.indexOf('Gas Station Coffee') gave 1, and a song that wasn't there gave -1.”

Level: Apprentice · More JavaScript terms at this level

Updated

In other subjects