Check if an Array Contains a Specific Value in JavaScript

In this tutorial, I’ll explain to you how you can check if an array contains a specific value or not in JavaScript.

Array in JavaScript:-

An array in JavaScript is a special variable that can hold more than one value.

We can declare an Array in JavaScript as follows:-

const arr=[
//output [ 'Mohit', 67 ]

You can also declare Array in JavaScript using a new keyword also as follows:-

const name=new Array('Mohit','Rohit');
console.log(name);  //it will print output as [ 'Mohit', 'Rohit' ]

Now let’s suppose we have an array name which has many values, and if we want to access a specific value then we can access it using it’s index number as follows:-

const name=new Array('Mohit','Rohit','Sobhit','Nakul','Atul');
//let suppose we want Mohit as output which is at index 0
//it will give output as Mohit

Now to check if an array contains a specific value or not

To check if an Array contains a particular value or not we have various ways to do it.

Here below I’ll discuss the two most common and easy ways to do it in JavaScript.

1. Using for Loop:- We can check it using for loop by traversing all the values present in the array if the value is found then we’ll return true as output otherwise we return as false as see the below code:-

let name=['Mohit','Rohit','Sobhit','Nakul','Atul'];
//now to check we declare a function
let value_Check=(value) =>{
    for(let i=0;i<name.length;i++)
        let current_Value=name[i];
            return true;
    return false;
//if the vlue is present in the array it will return 
//output as true othewise false




Using includes() method:-

This is the newest and easiest way in JavaScript to check the presence of the particular value in the array using Array.includes() function. If the value is not present in the array it will return false else it will return true.

let name=['Mohit','Rohit','Sobhit','Nakul','Atul'];
//declare value which you want to check

let val1='Mohit';
let val2='Sohbhit';
//using includes() function
//print true since val1 is present in the array
//print false since val2 is not present in the array




Also read: How to Check if Object is Empty in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *