JS Coding Questions Logo
JS Coding Questions
#244💼 Interview💻 Code

What is the purpose of compareFunction while sorting arrays

Advertisement

728x90

The compareFunction is used to define the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

Let's take an example to see the usage of compareFunction,

javascript
1let numbers = [1, 2, 5, 3, 4];
2
3numbers.sort((a, b) => b - a);
4
5console.log(numbers); // [5, 4, 3, 2, 1]

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 73

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
244of476
What is the purpose of compareFunction while sorting arrays | JSCodingQuestions.com