Solve - includes is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Joshua Hoehne

Solve - includes is not a function Error in JavaScript #

The "includes is not a function" error occurs when the includes() method is called on a value that is not of type string or array. To solve the error, convert the value to a string or array before calling the method or make sure to only call the includes method on strings or arrays.

typeerror includes is not a function

Here is an example of how the error occurs.

index.js
const str = 1234; // โ›”๏ธ Uncaught TypeError: str.includes is not a function const result = str.includes('3');

We called the includes method on a number and got the error. The includes method is only supported on strings or arrays.

To solve the error, either convert the value to a string or array before calling the method or only call the method if the value is of the correct type.

index.js
// ๐Ÿ‘‡๏ธ For Strings const num = 1234; const result1 = num.toString().includes('3'); console.log(result1); // ๐Ÿ‘‰๏ธ true // ๐Ÿ‘‡๏ธ For Arrays const set = new Set(['a', 'b', 'c']); const result2 = Array.from(set).includes('b'); console.log(result2); // ๐Ÿ‘‰๏ธ true

In the first example we convert the number to a string using the toString() method before calling the includes method.

In the second example, we used the Array.from method to convert a Set to an array before calling the includes method.

Alternatively, you can conditionally check if the value is of the correct type before calling the includes method.
index.js
const num = 1234; const result1 = typeof num === 'string' ? num.includes('3') : false; console.log(result1); // ๐Ÿ‘‰๏ธ false // ๐Ÿ‘‡๏ธ For Arrays const set = new Set(['a', 'b', 'c']); const result2 = Array.isArray(set) ? set.includes('b') : false; console.log(result2); // ๐Ÿ‘‰๏ธ false

In both examples we used the ternary operator, which is very similar to an if/else statement.

If the expression to the left of the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right is returned.

In the first example, we check if the value has a type of string. If it does, we return the result of calling the includes method on it, otherwise return false.

In the second example, we check if the value is an array using the Array.isArray method.

If the value is an array, we return the result of calling the includes method on it, otherwise return false.

If the error still persists, console.log the value you're calling theincludes method on and make sure it's either of type string or array.

If you have an object, there is a very good chance you have to access a specific property on the object that has a value of an array or string.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee