join() in JS – How to Join Array into String
Whenever you use join() on an array, the method does the following:
- It uses commas (or a user-defined value) to separate the array items.
- It joins all the array elements together into a new string.
- It returns the newly created string—without changing the original array.
Syntax of the join()
Method
join()
accepts only one argument. Here is the syntax:
Note the following:
- A comma (
,
) isjoin()
’s default separator. Therefore, if you do not specify aseparator
argument, browsers will use commas to separate the array’s elements. - Suppose the array has only one element. In that case, browsers will ignore the
separator
argument and return only the array item. - If the
separator
is an empty string (""
), JavaScript will join the array’s elements without using any character to separate them.
Examples
Below are examples of the join()
method.
How to join array elements with commas
In the example above, the browser automatically used a comma (,
) as the separator because we did not pass any argument into the join()
method.
How to join array elements with ", and "
How to join array elements without any separator
How to join array elements with " *** "
Learn the fundamentals of building and managing NPM packages from scratch.
Find out moreImportant Stuff to Know about the join()
Method
Here are two essential facts to remember when using the join()
method.
1. join()
converts undefined
and null
to empty strings
Suppose your array object contains an undefined
or null
element. In that case, join()
will convert such values to empty strings instead of "undefined"
or "null"
.
Here’s an example:
2. join()
parses empty slots as undefined
Suppose your array object has an empty slot. In that case, join()
will treat the slot as if it contains an undefined
value.
Here’s an example: