0
0
JavascriptHow-ToBeginner · 3 min read

How to Use includes Method in JavaScript: Syntax and Examples

The includes() method in JavaScript checks if a string or an array contains a specified value and returns true or false. For strings, it searches for a substring, and for arrays, it looks for an element. Use it like string.includes('text') or array.includes(value).
📐

Syntax

The includes() method has slightly different syntax for strings and arrays:

  • String: string.includes(searchString, position)
  • Array: array.includes(searchElement, fromIndex)

Parameters:

  • searchString / searchElement: The value to find.
  • position / fromIndex: Optional. The position to start searching from (default is 0).

Returns: true if found, otherwise false.

javascript
const str = 'Hello world';
const resultStr = str.includes('world', 0); // true

const arr = [1, 2, 3, 4];
const resultArr = arr.includes(3, 1); // true
Output
true true
💻

Example

This example shows how to use includes() to check if a string contains a word and if an array contains a number.

javascript
const sentence = 'The quick brown fox';
const hasWord = sentence.includes('quick');

const numbers = [10, 20, 30, 40];
const hasNumber = numbers.includes(25);

console.log('Contains "quick"?', hasWord);
console.log('Contains 25?', hasNumber);
Output
Contains "quick"? true Contains 25? false
⚠️

Common Pitfalls

Some common mistakes when using includes() are:

  • Using it on objects or types that don't support it (like plain objects).
  • For strings, includes() is case-sensitive, so 'Hello' and 'hello' are different.
  • For arrays, it uses strict equality (===), so includes(1) won't find '1'.
javascript
const text = 'Hello World';
console.log(text.includes('world')); // false because of case sensitivity

const arr = [1, 2, 3];
console.log(arr.includes('1')); // false because '1' is a string, not number
Output
false false
📊

Quick Reference

Summary tips for using includes():

  • Works on strings and arrays.
  • Returns true or false.
  • Optional second argument sets start position.
  • Case-sensitive for strings.
  • Uses strict equality for arrays.

Key Takeaways

includes() checks if a string or array contains a value and returns a boolean.
It is case-sensitive for strings and uses strict equality for arrays.
You can specify a start position to begin the search.
It only works on strings and arrays, not on other data types.
Use includes() to write clear and simple existence checks.