How to Use Join() Method to Combine Array of Strings in TypeScript?

In this tutorial, I will explain how to use TypeScript’s join() method to combine an array of strings into a single string. This method is particularly useful when you need to create a comma-separated list, format strings for display, or generate URLs from an array of parameters.

What Is The Join() Method in TypeScript

The join method in TypeScript is a built-in function that allows you to concatenate all elements of an array into a single string, with an optional separator between each element. This method is part of the Array prototype and can be used on any array of strings.

Syntax

array.join(separator?: string): string
  • separator: An optional parameter that specifies a string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (,).

Basic Example

Let’s start with a basic example to understand how the join method works. Suppose we have an array of city names in the USA:

const cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];
const result = cities.join(", ");
console.log(result); // Output: "New York, Los Angeles, Chicago, Houston, Phoenix"

In this example, the join method combines the city names into a single string, separated by a comma and a space.

Here is the exact output in the screenshot below:

Join() Method to Combine Array of Strings in TypeScript

Check out How to Find the Length of an Array in TypeScript?

Join() Method to Combine Array of Strings in TypeScript Examples

Now, let me show you some examples of using the join() method in TypeScript to combine the array of strings.

1. Create a Mailing List

Imagine you are developing a feature for a web application that requires sending an email to multiple recipients. You have an array of email addresses and need to format them into a single string separated by semicolons (;).

const emailAddresses = ["john.doe@example.com", "jane.smith@example.com", "alice.johnson@example.com"];
const mailingList = emailAddresses.join("; ");
console.log(mailingList); // Output: "john.doe@example.com; jane.smith@example.com; alice.johnson@example.com"

2. Generate a URL Query String

Another common use case is generating a URL query string from an array of parameters. For example, you might have an array of search terms that need to be included in a URL.

const searchTerms = ["typescript", "join method", "tutorial"];
const queryString = searchTerms.join("&");
const url = `https://www.example.com/search?q=${queryString}`;
console.log(url); // Output: "https://www.example.com/search?q=typescript&join method&tutorial"

Here is the exact output in the screenshot below:

Join() Method to Combine Array of Strings in TypeScript Examples

3. Format a List of Names

Suppose you are working on a web application that displays a list of attendees for an event. You have an array of attendee names and need to format them into a string for display.

Here is the TypeScript code that you can use.

const attendees = ["John Doe", "Jane Smith", "Alice Johnson", "Bob Brown"];
const formattedAttendees = attendees.join(", ");
console.log(formattedAttendees); // Output: "John Doe, Jane Smith, Alice Johnson, Bob Brown"

Check out Clear an Array in TypeScript While Preserving Its Type

4. Empty Array

If the array is empty, the join method will return an empty string.

const emptyArray: string[] = [];
const result = emptyArray.join(", ");
console.log(result); // Output: ""

5. Single Element Array

If the array contains only one element, the join method will return that element as a string without any separators.

const singleElementArray = ["Only One"];
const result = singleElementArray.join(", ");
console.log(result); // Output: "Only One"

6. Combine Multiple Arrays

You can also use the join method in conjunction with other array methods to combine multiple arrays into a single string. For example, let’s say you have two arrays of city names and you want to create a single, formatted string.

const eastCoastCities = ["New York", "Boston", "Philadelphia"];
const westCoastCities = ["Los Angeles", "San Francisco", "Seattle"];
const allCities = [...eastCoastCities, ...westCoastCities];
const formattedCities = allCities.join(", ");
console.log(formattedCities); // Output: "New York, Boston, Philadelphia, Los Angeles, San Francisco, Seattle"

Here is the exact output in the screenshot below:

TypeScript Join() Method to Combine Array of Strings

7. Using Custom Separators

The join method allows you to use any string as a separator. This is particularly useful when you need to format strings in a specific way. For example, you might want to use a pipe (|) as a separator.

const states = ["California", "Texas", "Florida", "New York"];
const formattedStates = states.join(" | ");
console.log(formattedStates); // Output: "California | Texas | Florida | New York"

8. Combine Strings with Special Characters

You can also use the join method to combine strings that contain special characters. For example, if you have an array of file paths, you can use the join method to create a single path.

const filePaths = ["/home/user", "documents", "typescript", "tutorial.txt"];
const fullPath = filePaths.join("/");
console.log(fullPath); // Output: "/home/user/documents/typescript/tutorial.txt"

Check out How to Get the Last Element of an Array in TypeScript?

Best Practices

Here are some of the best practices you can follow while working with the join() method in TypeScript array.

Using Descriptive Variable Names

When using the join method, it’s important to use descriptive variable names to make your code more readable and maintainable. Instead of using generic names like array and result, use names that describe the data and the purpose of the operation.

const cityNames = ["Miami", "Dallas", "Denver"];
const formattedCityNames = cityNames.join(", ");
console.log(formattedCityNames); // Output: "Miami, Dallas, Denver"

Handle Null or Undefined Values

If your array might contain null or undefined values, you should handle them appropriately before using the join method. One way to do this is by using the filter method to remove any null or undefined values.

const mixedArray = ["San Diego", null, "Austin", undefined, "Las Vegas"];
const filteredArray = mixedArray.filter((item) => item !== null && item !== undefined);
const formattedArray = filteredArray.join(", ");
console.log(formattedArray); // Output: "San Diego, Austin, Las Vegas"

Using Template Literals for Complex Strings

For more complex string formatting, consider using template literals in combination with the join method. This allows you to include variables and expressions directly within the string.

const firstName = "John";
const lastName = "Doe";
const hobbies = ["hiking", "photography", "coding"];
const introduction = `My name is ${firstName} ${lastName} and I enjoy ${hobbies.join(", ")}.`;
console.log(introduction); // Output: "My name is John Doe and I enjoy hiking, photography, coding."

Conclusion

The join method in TypeScript is used for combining array elements into a single string. Whether you’re creating a mailing list, generating a URL query string, or formatting a list of names, the join method provides a simple and efficient way to achieve it. I hope now you got an idea of using the join() method in TypeScript to combine array of strings.

You may also like: