How to Check if Value is not Exists of Array in Javascript?

Sep 01, 2022 . Admin



Hello dev,

I am going to explain you example of how to check if value is not exists of array in javascript. We will use check if value is not exists in array using javascript. We will look at example of javascript add to array if not exists code example.

In this example, we will explain to you to check if the value does not exist in the array in javascript. if you check if the value exists or not in the array you have to use include(), it is used in the if condition, and push the element if it's not already present.

In the second example we have another method to check if the value exists or not.indexOf() method is same as include() method it is used in condition.The indexOf() method returns the first index (position) of a specified value

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Check if Value is not Exists of Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Check if Value is not Exists of Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const fruits = ['Banana','Mango','Graps','Kiwi'];
            const fruits2 = 'Orange';
            //use include() method..
            if(!fruits.includes(fruits2)){
               fruits.push(fruits2); 
            }

            //give output to console..
            console.log(fruits);
        </script>
    </body>
</html>
Output:
['Banana', 'Mango', 'Graps', 'Kiwi', 'Orange']
Example: 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Check if Value is not Exists of Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Check if Value is not Exists of Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            var colors = ['Red','Yellow'];
            var item = 'Green';
            //use indexOf() method..
            if(colors.indexOf(item) === -1){
               colors.push(item); 
            }

            //give output to console..
            console.log(colors);
        </script>
    </body>
</html>
Output:
['Red', 'Yellow', 'Green']
I hope it will help you...
#Javascript