Boyan Iliev

How to Check if an Array Includes a Value in JavaScript

Created June 22, 2021

Introduction

The array is almost always used in your or someone's code. It is a very important part of programming and you probably couldn't do the stuff that you want to do without arrays.

But what happens when your array gets so big you forget all the values that are stored in it. You could probably check through the whole array just so you can check for that one certain element. Luckily for us, there is a method that was created so you don't have to lose your time looking through all the values inside. This method is called includes().

includes()

Let's create an array with a couple of elements.

let sites = ['DevDojo', 'Facebook', 'Twitter', 'YouTube'];

Now let's imagine that there are much more values stored in this array and we forget which ones are stored there and which aren't. In order to use the method we just have to write our arrays name, add the method, and then put in the value that we are looking for.

If the value we are looking for is in the array, the output will be a true boolean value. If the value isn't in the array we will see a false value returned.

sites.includes('DevDojo');
<- true
----------------
sites.includes('Netflix');
<- false

This is how you can check if an array includes a certain value and it is the easiest way to check it.

Conclusion

Arrays can be scary sometimes when you don't know what to do, but knowing a method like this one can help you a ton.

I hope that this post has helped you and I would love to hear your feedback down in the comments.

Random Dev Meme

meme