Wednesday 10 July 2019

javascript - Sort strings by using "less/greater than" comparison operators in comparator

Today I found a strange for me implementation of strings sorting:



['Data', 'Chata', 'Clata'].sort(function(a, b) { return a > b});



Using this approach we take a valid sorted array as the output - ["Chata", "Clata", "Data"].
But I don't clearly understand why it works...



I know that comparator function expects three different outputs - zero, integer above zero, integer below zero. But in this case we can take only two values - true (if a greater than b) or false (if a less than b) (1 or 0 after type coercion).



Can anybody explain me why it works?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...