JavaScript TypeError – Invalid Array.prototype.sort argument

This JavaScript exception invalid Array.prototype.sort argument occurs if the parameter of Array.prototype.sort() is not from either undefined or a function which sorts accordingly.

Message:

TypeError: argument is not a function object (Edge)
TypeError: invalid Array.prototype.sort argument (Firefox)

Error Type:

TypeError

Cause of the Error: The argument is passed to the sort() method should be either undefined or a function which compares its operands.

Example 1: In this example, argument passed to sort() method is not expected, So the error has occurred.



HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
[2, 5, 6, 1, 3].sort(3); // error here
</script>

chevron_right


Output:

TypeError: argument is not a function object

Example 2: In this example, argument passed to sort() method is not expected, So the error has occurred.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
var compareFun = { 
    Asc: (a, b) => a >= b, 
    Dsc: (a, b) => a <= b 
};
  
// TypeError
[1, 2, 3, 6, 5, 8].sort(
    compareFun[this.key] || 'Asc');
</script>

chevron_right


Output:

TypeError: argument is not a function object

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.