What's In My Array
Mastering Array Search with some, indexOf, and includes in JavaScript

I have been a full-stack developer for twelve years and am currently part of the Cloud FinOps team at Atlassian. I previously ran an App development agency, managing various teams across design and development, leading web, backend and native mobile app developers in Australia and Europe. My strengths are system architecture design and communicating complicated tech to everyday people. Having helped scale tech at numerous startups, I am passionate about making a positive difference. When not working, you can find me writing tech articles and teaching Javascript and React at SheCodes, an initiative helping to get more women into tech. I regularly give talks on various topics, focusing on the impact the technology we build can have. I am devastated by the state of the world, love a good political rant and can often be swearing at no one in particular. I enjoy building things in JavaScript, Deno and Node.
Arrays are some of the most common data types you work with as a programmer. We filter them, we map over them, we edit them and more. As we spend so much time with them, JavaScript has created some great helper functions to make them easier to work with. Let's look at checking if an array contains a specific value. Say we have a list of IDs and want to check if a given ID is inside the array.
We could use indexOf which returns the first index the given value can be found at or -1 if not present.
const ids = [1, 2, 3, 4, 5];
const idToCheck = 3;
const exists = ids.indexOf(idToCheck) !== -1;
console.log(exists) // true
Great if we want to grab the index simultaneously, but in this case, I don't care about the index. We could use some that checks if at least one element matches the given value.
const ids = [1, 2, 3, 4, 5];
const idToCheck = 3;
const exists = ids.some(id => id === idToCheck);
console.log(exists); // true
Nice, but now I am passing a function. I think we can slim this down by using includes which returns a boolean if the array contains the passed value.
const ids = [1, 2, 3, 4, 5];
const idToCheck = 3;
const exists = ids.includes(idToCheck);
console.log(exists); // true
We have covered a few array methods here, but I love includes it turns some validation checks into one-liners. All these methods have full browser support, but you can find a breakdown in the links below.



