.indexOf() Method

The .indexOf() method can be used to determine where an element is located in the array. Duplicates give the index of the first instance. Let's use the letters of the alphabet and figure out what letter q is.

var alphabet = "a b c d e f g h i j k l m n o p q r s t u v w x y z";

var alphaQ = alphabet.split(" ").indexOf("q");

alphaQ += 1;
console.log(alphaQ);

You should have gotten 17. Let's break this down:

  • I put the .split() and .indexOf methods together to show you that you can combine methods, and also just to save time and space.

  • I added one to alphaQ before logging it to the console because arrays are zero-indexed.

Last updated