Free UI Resources - UI Dev Made Easy
Javascript

Javascript Array Methods – .includes()

.includes()

The .includes() method is a built-in function in JavaScript that allows you to check if an array contains a specific element. It returns a boolean value (true or false) based on whether the element is found in the array or not.

Here’s the basic syntax of the .includes() method:

const isIncluded = array.includes(element);
  • element: The element you want to check for in the array.
  • isIncluded: A boolean indicating whether the element is found in the array (true) or not (false).

Here’s an example to illustrate how .includes() works:

const fruits = ['apple', 'banana', 'orange'];

const hasBanana = fruits.includes('banana');
const hasGrapes = fruits.includes('grapes');

console.log(hasBanana);  // Output: true
console.log(hasGrapes);  // Output: false

In this example, the .includes() method is used to check if the array fruits contains the strings 'banana' and 'grapes'. The result is true for 'banana' and false for 'grapes'.

Keep in mind the following points when using .includes():

  1. Returns Boolean: The .includes() method returns true if the specified element is found in the array, and false otherwise.
  2. Case Sensitivity: .includes() performs a case-sensitive search. So 'Apple' and 'apple' would be considered different elements.
  3. NaN Comparison: .includes() can be used to check for the presence of NaN in an array.
  4. IndexOf vs. Includes: .includes() is a more concise and straightforward way to check for the existence of an element in an array compared to using .indexOf(), which returns the index of the element if found, or -1 if not found.
  5. Use Cases: .includes() is handy when you want to quickly determine whether a particular element exists in an array without needing its index.
  6. Comparison with Primitives: When comparing non-primitive values (like objects or arrays), .includes() uses strict equality (===) to check for equality.

In summary, the .includes() method is a convenient way to check if an array contains a specific element. It’s useful for quickly determining whether a value is present in an array without the need for complex logic or iterations.

back to top