Can somebody explain to me this function:
function(a, b) { return a - b };
versus:
function(a, b) { return a > b};
?
thank you!
Can somebody explain to me this function:
function(a, b) { return a - b };
versus:
function(a, b) { return a > b};
?
thank you!
Assuming that both a
and b
are numbers, the first function returns a number. The second one returns boolean.
Suppose a = 5
and b = 3
. The first one will yield 2
. The second one will yield true
.
i assume u use this function for sorting?
if a = 'a'
and b = 'b'
Then with first function it will return negative value
cause
97-98 === -1
then because it is negative it needs to be swaped
but also if u return false like in second case
function(a, b) { return a > b};
it is swaped because returned value is false
try here above in repl to change fourth line to return false;
or return undefined;
it is equal
false to negative number
undefined to zero
true to positive number
Also if u donβt specify this function parameter to ur .sort
function
then it will compare values by strings
etc if u have [40, 100, 1, 5, 25, 10]
it will convert to ["40", "100", "1", "5", "25", "10"]