Home >>JavaScript Array Reference >JavaScript Array sort() Method

JavaScript Array sort() Method

JavaScript Array sort() Method

JavaScript sort() method is used to sort the items of a given input array according to the compare() function. If the function is not given then it sorts the values as strings in alphabetical and ascending order. It changes the original given array.

Syntax:
array.sort(compareFunction)

Parameter Values

Parameter Description
compareFunction This is an optional parameter. It defines a function that defines an alternative sort order.

Browser Support

Method Chrome Edge Firefox Safari Opera
sort() Yes Yes Yes Yes Yes
Here is an example of JavaScript sort() method:
<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var x = ["Bunny", "Mike", "Jerry", "Joker", "Alpha", "Delta"];
document.getElementById("demo").innerHTML = x;
function myFunction() 
{
  x.sort();
  document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.

Example 2:
<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction1()">Try it</button>
<p id="demo1"></p>
<script>
var num = [34, 96, 3, 6, 63, 1, 14];
document.getElementById("demo1").innerHTML = num;
function myFunction1() 
{
  num.sort(function(a, b){return a-b});
  document.getElementById("demo1").innerHTML = num;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.