Solve - join is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 20, 2021

banner

Check out my new book

Solve - join is not a function Error #

The "TypeError: join is not a function" occurs when we call the join() method on a value that is not an array. To solve the error, make sure to only call the join method on valid arrays.

typeerror join is not a function

Here is an example of how the error occurs.

index.js
const arr = {}; // ⛔️ Uncaught TypeError: join is not a function const result = arr.join(',');

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

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

index.js
const arr = ['one', 'two', 'three']; const result = arr.join(','); // 👇️ "one,two,three" console.log(result);

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

index.js
const arr = null; const result = Array.isArray(arr) ? arr.join(',') : ""; console.log(result); // 👉️ ""

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 join method on it, otherwise we return an empty string. 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 join method on it.

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

index.js
const set = new Set(['one', 'two', 'three']); const result = Array.from(set).join(','); console.log(result); // 👉️ "one,two,three"

Before calling the join method, we convert the value to an array.

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

index.js
const set = new Set(['one', 'two', 'three']); const result = [...set].join(','); console.log(result); // 👉️ "one,two,three"
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.