Last updated: Mar 3, 2024
Reading timeยท3 min
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.
Here is an example of how the error occurs.
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.
Array.join()
method on arraysTo solve the error, console.log
the value you're calling the join
method on
and make sure it's a valid array.
const arr = ['bobby', 'hadz', 'com']; const result = arr.join(','); // ๐๏ธ "bobby,hadz,com" console.log(result);
join()
You can conditionally check if the value is an array by using the Array.isArray method.
const arr = null; const result = Array.isArray(arr) ? arr.join(',') : ""; console.log(result); // ๐๏ธ ""
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 join
method.
Otherwise, we return an empty string.
This way, you won't get an error, even if the value is not an array.
You can also use a simple if
statement to check if the value is an array.
const arr = null; let result = ''; if (Array.isArray(arr)) { result = arr.join(','); } console.log(result); // ๐๏ธ ""
If the arr
variable stores an array, the if
block runs where we call the
join()
method.
join()
If you have an array-like object, use the Array.from()
method to convert it to
an array before calling join()
.
const set = new Set(['bobby', 'hadz', 'com']); const result = Array.from(set).join(','); console.log(result); // ๐๏ธ "bobby,hadz,com"
We used the Array.from()
method to convert a Set
object to an array to be
able to use the Array.join()
method.
You could achieve the same result by using the spread syntax (...).
const set = new Set(['one', 'two', 'three']); const result = [...set].join(','); console.log(result); // ๐๏ธ "one,two,three"
join()
If you have an object that has an array property, access the property before
calling the join()
method.
const obj = { site: ['bobby', 'hadz', 'com'], }; const result = obj.site.join(', '); console.log(result); // ๐๏ธ bobby, hadz, com
We accessed a property on the object that stores an array to be able to call the
join()
method.
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.
Also, ensure you have parsed it to a native JavaScript array before calling the
join
method on it.
The Array.join() method concatenates all of the elements in an array using a separator.
The only argument the Array.join()
method takes is a separator
- the string
used to separate the elements of the array.
If a value for the separator
argument is omitted, the array elements are
joined with a comma ,
.
If the separator
argument is set to an empty string, the array elements are
joined without any characters in between them.