Solve - concat is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

Solve - concat is not a function Error #

The "concat is not a function" error occurs when we call the concat() method on a value that is not an array. To solve the error, convert the value to an array before calling the concat() method or make sure to only call the concat method on valid arrays.

typeerror concat is not a function

Here is an example of how the error occurs.

index.js
const arr1 = {name: 'Tom'}; const arr2 = [{name: 'James'}]; // โ›”๏ธ TypeError: concat is not a function const arr3 = arr1.concat(arr2);

We called the Array.concat() method on an object and got the error back.

To solve the error, console.log the value you're calling the concat method on and make sure it's a valid array.

index.js
const arr1 = [{name: 'Tom'}]; const arr2 = [{name: 'James'}]; const arr3 = arr1.concat(arr2); // ๐Ÿ‘‡๏ธ [{name: 'Tom'}, {name: 'James'}] console.log(arr3);

You can conditionally check if the value is an array by using the Array.isArray method.

index.js
const arr1 = null; const arr2 = [{name: 'James'}]; const arr3 = Array.isArray(arr1) ? arr1.concat(arr2) : []; console.log(arr3); // ๐Ÿ‘‰๏ธ []

We used a ternary operator, which is very similar to an if/else statement.

If the value is an array, we return the result of calling the concat method on it, otherwise we return an empty array. This way, you won't get an error, even if the value is not an array.

If the value is fetched from a remote server, make sure it is of the type you expect it to be by logging it to the console and make sure you have parsed it to a native JavaScript array before calling the concat method.

If you have an array-like object which you're trying to convert to an array before calling the concat method, use the Array.from method.

index.js
const set1 = new Set(['a', 'b']); const arr1 = ['c', 'd']; const result = Array.from(set1).concat(arr1); console.log(result); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

Before calling the concat method, we convert the Set object to an array.

You could achieve the same result by using the spread syntax (...).

index.js
const set1 = new Set(['a', 'b']); const arr1 = ['c', 'd']; const result = [...set1].concat(arr1); console.log(result); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

This approach would also work if you're working with a NodeList or other array-like objects.

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