Home » Programming » Javascript » Javascript Includes In Array

Checking an Array Contains a Value in JavaScript [Examples]

This article will show you how to check if a value is in an array in the JavaScript programming language. Code examples to check whether an array includes a value are provided.

Arrays in JavaScript

Arrays are a type of variable that hold an ordered list of values. Each value in an array has a position within the array, called the index. The index can be used to access each value in the array.

Indexes are integer values, which start counting from 0 (zero) for the first item in the array – so the first item in an array is at index 0, the second item is at index 1, and so on

Arrays can hold any kinds of values, and references to other variables – they’re a flexible way of storing a list of values or objects of any length – from the rows in a table to the enemies on-screen in a video game.

The includes() Method to Search for an Element in an Array

The includes() method is built in to the JavaScript array type and is available on any array value or variable. When called, it will return true or false depending on whether the array it is called from contains the specified value

JavaScript includes() Method Syntax

The syntax for the JavaScript Array includes() method is as follows:

array.includes(searchFor, fromIndex)

Note that:

  • array is any array value or variable
  • searchFor is the element you wish to search the array for
  • fromIndex is the index position to start searching the array
    • Matching values previous to this index will be ignored
    • If not specified, it will default to 0 (searching from the beginning of the array)
    • If it is larger than or equal to the array length, false will be returned
    • A negative fromIndex can be supplied to start searching from a specified position from the end of the array
      • The search will still move forward! It’s just the starting position that’s specified using a negative position
  • A boolean (true/false) value is returned
    • true if the element is present in the array, false if it is not

includes() Method Code Examples

Here are some examples of the array includes() method using different array values:

[1, 2, 3].includes(1)         // true
[1, 2, 3].includes(5)         // false
[1, 2, 3].includes(3, 3)      // false
[1, 2, 3].includes(3, 2)     // true
[1, 2, 3].includes(3, -2)     // true
[1, 2, NaN].includes(NaN)     // true
["dog", "cat", "fish"].includes("bird")   // false
["dog", "cat", "fish"].includes("fish")   // true

 

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment