JavaScript Convert an Array to Comma Separated String

avatar
Published: Dec 02, 2022

Hello devs, today I'll show you how to convert an Array into a comma-separated string. Sometimes we need to run in a situation where we need to convert our array into a comma-separated string. We can achieve our expected result in two ways. We'll see both ways. So, no more let's see how we can easily convert our array into comma separated string in a javascript way.

Example 1 : using toString() method

In the first example, we'll use toString() method. Let's see the below code snippet

<html>
<head>
    <title>How to Convert an Array into Comma Separated String? - shouts.dev</title>
</head>
<body>
  
<script>
    var languages = ['PHP', 'LARAVEL', 'VEUJS', 'JavaScript'];
    console.log(languages.toString());

</script>
</body>
</html>

toString() method is a short and convenient method method for convert an array into comma separated string. For more info you can see this doc. So, above code snippet will produce the below output

Convert Array into Comma Separated String using toString() method

Example 2 : using join() method

In the second example, we'll use join() method. Let's see the below code snippet

<html>
<head>
    <title>How to Convert an Array into Comma Separated String? - shouts.dev</title>
</head>
<body>
  
<script>
    var languages = ['PHP', 'LARAVEL', 'VEUJS', 'JavaScript'];
    console.log(languages.join(','));
</script>
</body>
</html>

join() method is a very handy method. You cannot only convert into comma separated rather then any string or symbol you provide as parameter like join('='); See the doc for more info. So, above code snippet also produce the same output as we seen in example1.

Convert Array into Comma Separated String using join() method

That's it for today. Hope you've enjoyed this tutorial. If you've any questions or face any difficulty, catch me in the comment section. Thanks for reading. 🙂

Comments

No comments yet…