The .join() method creates and returns a new string by concatenating all the elements in an array, separated by a specified separator string. If the array has only one item, that item will be returned without using the separator.
1. Basic Syntax
array.join(separator)
separator (Optional): A string to separate each pair of adjacent elements.
- If omitted, the elements are separated with a comma (“,”).
- If provided as an empty string (“”), all elements are joined without any characters between them.
2. Examples of Use
A. Default Join (Comma)
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// Output: "Fire,Air,Water"
B. Different Separators
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join(' - '));
// Output: "Fire - Air - Water"
console.log(elements.join(''));
// Output: "FireAirWater"
C. Joining with New Lines
This is particularly useful when formatting data for display in consoles or text areas.
const list = ['Step 1', 'Step 2', 'Step 3'];
console.log(list.join('\n'));
/* Output:
Step 1
Step 2
Step 3
*/
3. Handling Special Values
The .join() method has specific rules for non-string values:
- null or undefined: These are converted to empty strings (“”).
- Objects: Objects are converted using their .toString() method (usually resulting in “[object Object]”).
- Nested Arrays: Nested arrays are flattened/stringified recursively.
const mixed = ['Hello', null, 'World', undefined];
console.log(mixed.join(' '));
// Output: "Hello World " (notice the extra spaces)
4. Common Use Cases
Creating Slugs for URLs
const title = ["How", "to", "learn", "JavaScript"];
const slug = title.join("-").toLowerCase();
console.log(slug); // "how-to-learn-javascript"
Reversing a String
Since JavaScript doesn’t have a native string.reverse() method, developers often use split, reverse, and join together.
const str = "JavaScript";
const reversed = str.split("").reverse().join("");
console.log(reversed); // "tpircSavaJ"
