How to use .join method in Javascript

By FoxLearn 12/18/2024 8:11:25 AM   86
The `.join()` method in JavaScript is used to join all elements of an array into a single string. It takes an optional `separator` parameter that specifies how the elements should be separated in the resulting string.

If no separator is provided, the elements are joined with a comma by default.

For example, consider the following array:

const fruits = ["apple", "banana", "orange"];

If we call the .join() method on an array without passing any separator, the array elements are joined with a comma (,) by default.

const result = fruits.join();

The resulting string will be:

"apple,banana,orange"

If we pass a separator as an argument, such as a hyphen (-), the .join() method will join the array elements with the specified separator between them.

const result = fruits.join("-");

The resulting string will be:

"apple-banana-orange"