How to Convert a Set to a String in JavaScript

To convert a set to a string in JavaScript, call the Array.from() method with the Set as an argument, then call the join() method on the resulting array. For example:

const set = new Set(['x', 'y', 'z']);

const str1 = Array.from(set).join(' ');
console.log(str1); // x y z

const str2 = Array.from(set).join(',');
console.log(str2); // x,y,z

The Array.from() method converts an array-like object like a Set into an array:

const set = new Set(['x', 'y', 'z']);

console.log(Array.from(set)); // [ 'x', 'y', 'z' ]

After the conversion, we can call the join() method on the array. join() returns a string containing the elements of an array concatenated with the specified separator:

console.log(['x', 'y', 'z'].join('-')); // x-y-z

console.log(['x', 'y', 'z'].join('/')); // x/y/z

Note: We can also use the spread syntax (...) to convert a Set to an array:

const set = new Set(['x', 'y', 'z']);

const str1 = [...set].join(' ');
console.log(str1); // x y z

const str2 = [...set].join(',');
console.log(str2); // x,y,z

The spread syntax unpacks the values of the Set into a new array that we call join() on to get the string.



Subscribe to Coding Beauty Newsletter

Gain useful insights and advance your web development knowledge with weekly tips and tutorials from Coding Beauty. Over 2,000 developers subscribe.

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.


Leave a Comment

Your email address will not be published. Required fields are marked *