JavaScript Array sort()

The JavaScript array sort() method is used to return the element of the given array in a sorted order.

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
array.sort(compareFunction)
array.sort(compareFunction)
array.sort(compareFunction)

Parameters:
compareFunction: It represents a function that provides the functionality of sort order. It is an optional parameter.

Returns:
An array with sorted elements.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<script>
var a = ["GOLD","SILVER","DIAMOND","RUBY","PLATINUM"]
var result=a.sort();
document.writeln(result);
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <script> var a = ["GOLD","SILVER","DIAMOND","RUBY","PLATINUM"] var result=a.sort(); document.writeln(result); </script> </body> </html>
<!DOCTYPE html>
<html>
<body>
<script>
var a = ["GOLD","SILVER","DIAMOND","RUBY","PLATINUM"]
var result=a.sort();
document.writeln(result);
</script>
</body>
</html>