JavaScript Tutorial – Array Methods

Convert Array To String

toString() method converts an array to a comma separated string.

How to list array as string in JavaScript

<script type="text/javascript">
   var web = ["CSS", "HTML", "JavaScript", "PHP"]; 
   var webText = web.toString();
</script>
Try it yourself »

How to change separator for array in JavaScript

<script type="text/javascript">
   var webText = web.push(" - ");
</script>
Try it yourself »

join() method works the same as toString() method, except that you can specify a separator with join() method.

Remove Element

pop() methods remove the last element from an array.

How to remove last element from an array in JavaScript

<script type="text/javascript">
   web.pop();
</script>
Try it yourself »

Add Element

push() method adds an element to the end of the array.

How to add element to an array in JavaScript

<script type="text/javascript">
   web.push("XML");
</script>
Try it yourself »

Change Element

You can access the element of an array using index and change it to any value you wish.

How to change an element of an array

<script type="text/javascript">
   web[0] = "jQuery";
</script>
Try it yourself »

Sorting an Array

sort() method sorts an array alphabetically.

How to sort an array

<script type="text/javascript">
   web.sort();
</script>
Try it yourself »

Reversing an Array

reverse() sorts an array in descending order.

How to sort an array in descending order

<script type="text/javascript">
   web.sort(); //sort the array alphabetically first
   web.reverse(); //now reverse the sort order, which is in descending order
</script>
Try it yourself »

Concatenate Arrays

concat() method creates a new array by joining two arrays.

How to concatenate arrays

<script type="text/javascript">
   var web1 = ["HTML","CSS"];
   var web2 = ["PHP"];
   var web3 = web1.concat(web2);
</script>
Try it yourself »