A needle shown in closeup against pale yellow straw

Searching through arrays has traditionally involved writing an exhaustive loop that inspected each element in the array, checking if they matched a particular value. Thankfully, modern JavaScript provides two solutions that are far more efficient: one new in JS 2015, and one a little older.

includes

We’ll start with the most recent: includes. Very simply, includes returns a value of true or false if an array contains a particular value. Given an array of the following elements:

let stations = [ "Salyut", "Skylab", "Almaz", "Mir", "ISS", "Tiangong" ]

Determining if the array contains a particular value is as simple as the following (tested in the console for clarity):

stations.includes("Skylab");
> true

stations.includes("Space Station V");
> false

Note that includes will only match complete elements, and not partial strings:

stations.includes("Sky");
> false

Searches are also case-sensitive:

stations.includes("skylab");
> false

includes will tell you if an array contains a matching element, but it won’t tell you where that element is in the array. However, you can tell it where to start searching by adding an optional position argument:

stations.includes("Mir", 2);
> true

stations.includes("Mir", 5);
> false

includes has decent support, in recent browser versions: Chrome 47, Firefox 43. Microsoft Edge, and Safari 9. There’s no support in Internet Explorer, but polyfills.io and other sources can provide a solution.

indexOf

indexOf tells you the position of a matching element in an array. Given the same array we started with:

let stations = [ "Salyut", "Skylab", "Almaz", "Mir", "ISS", "Tiangong" ];

We can use indexOf to detect the position of an element that matches a particular value:

stations.indexOf("ISS");
> 4

indexOf returns -1 if the element is not found:

stations.indexOf("Elysium");
> -1

The method has excellent support in every modern browser, including IE9+. Like includes, you can add an optional argument for where in the array you want to start searching from.

lastIndexOf

indexOf finds the first match from the start of an array. In contrast, lastIndexOf starts searching from the end of the array.

stations.lastIndexOf("Almaz");
> 2

Note that lastIndexOf still reports the position of a match indexed from the start, and (like indexOf) will return -1 if no match is found. Also like indexOf, an optional argument can be provided, but it indicates the point from the end of the array where the search should start from. As you might expect, lastIndexOf has the same range of browser support as indexOf.

Photograph by T Buchtele, used under a Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.