Solve - concat is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Check out my new book

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, which caused the error.

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 the 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, 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 ensure you have parsed it to a native JavaScript array before calling the concat method.

If you have an array-like object, use the Array.from() method to convert it to an array before calling the concat 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']

We converted the Set object to an array before calling the concat method.

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.