Skip to content

JavaScript if in array | Example code

  • by

Use JavaScript includes() method to check if the value in Array. This method returns true if an array contains a specified value otherwise returns false if the value is not found.

array.includes(element, start)

Note: The includes() method is case-sensitive.

JavaScript if in array

Simple example code check if the string is in array js.

<!DOCTYPE html>
<html>
<body>

  <script>

    var colors = ["red", "blue", "green"];
    var hasRed = colors.includes("red"); 
    var hasYellow = colors.includes("yellow"); 

    console.log(hasRed)
    console.log(hasYellow)

  </script>

</body>
</html> 

Output:

JavaScript if in array

You can also use Array#indexOf, which is less direct, but doesn’t require polyfills for outdated browsers.

console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); //true

Note: Array.includes() is more straightforward and easier to use for checking the presence of an element in an array. However, if you need the index of the element, then Array.indexOf() is more appropriate.

Many frameworks also offer similar methods:

Note: that some frameworks implement this as a function, while others add the function to the array prototype.

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading