Converting an Array to string in JavaScript

JavaScript has some inbuilt method which easily converts an Array to string.

You traverse on the Array and concat value to a variable with a separator for string conversion if you are not familiar with methods.

Converting an Array to string in JavaScript


Contents

  1. Loop
  2. toString()
  3. join()
  4. Conclusion

 

1. Loop

Traverse through an Array until the variable value is less than Array length and concatenate array value to a string variable.

Example

<script type='text/javascript'>
 // Array
 var num_arr = [23,1,65,90,34,21];

 // Array length
 var arr_len = num_arr.length;

 var num_str = '';
 
 // Traverse
 for(var i=0;i< arr_len; i++){

  // Concat Array value to string variable
  num_str += num_arr[i];

  // Add separtor
  if(i < (arr_len-1) ){
   num_str += ',';
  }
 }

 console.log( num_str );
</script>

Output

23,1,65,90,34,21

 

2. toString()

This converts an Array to string and returns a comma separated value.

Note – Its default separator is the comma(,) and it doesn’t allow to specify separator.

Syntax –

Array.toString();

Example

<script type='text/javascript'>
 // Array
 var names_arr = ['Yogesh','Sonarika','Vishal','Aditya'];

 // Array conversion
 var names_str = names_arr.toString();

 console.log( names_str );
</script>

Output

Yogesh,Sonarika,Vishal,Aditya

 

3. join()

It also converts an Array to String and allows to specify separator. Its default separator is the comma(,) .

Syntax –

Array.join();

Or

Array.join( separator );

Example

<script type='text/javascript'>
 // Array
 var names_arr = ['Yogesh','Sonarika','Vishal','Aditya'];

 // Array conversion
 var names_str = names_arr.join(' - ');
 
 console.log('names : ' + names_str);
</script>

Output

Yogesh - Sonarika - Vishal - Aditya

 

4. Conclusion

I showed how you can convert an Array to string with Loop and inbuilt JavaScript methods. You can use the inbuilt methods for one line conversion.

If you want to execute some code while conversion then use Loop e.g. check Array value before concatenate.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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