.includes() Method

  • Array Method
  • Array Methods
  • Code
  • JavaScript

The .includes() array method checks if a certain specified value can be found in an array. Say you have a nut allergy and while you're out to eat you need to check the ingredients of a dessert you want to order to see if it contains nuts. Programatically you would do that with .includes() in JavaScript.

const ingredients = ["eggs", "nuts", "cream", "sugar"];
console.log(ingredients.includes("nuts"));// expected output: true
console.log(ingredients.includes("meat"));// expected output: false

.includes() defaults to searching at position 0 in the array, but it can take an optional second argument, which is the value of the position where you want to start searching from. If it's a positive value, it starts at arr[positive value], and if it's a negative value, it starts at arr[array.length + negative value]. It always moves from the beginning of the array to the end of the array, regardless of whether this optional position value is positive or negative.

const chores = ["dishes", "sweep", "vacuum", "dust", "laundry", "fold clothes"];
console.log(chores.includes("sweep", 2));// expected result: false
console.log(chores.includes("fold clothes", -2));// expected result: true

It's worth noting that the difference between .some() and .includes() is that .some() will take a condition that you pass as a callback, and the boolean that gets returned is based on that condition being met or not met, whereas .includes() is simply looking for the value you specifically pass to the method. You would use .some() to search for an even number within the array, and you would use .includes() to see if an array includes the number 2, the number 4, or any other specific value.

From MDN: The .includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

See more examples and documentation here.