if (cellA > cellB) return 1;
if (cellA < cellB) return -1;
if (cellA === cellB) return 0;
Why is the switch better?
Or even (less explicit, but shorter code): if (cellA === cellB) return 0;
return cellA > cellB ? 1 : -1; if (cellA > cellB) return 1;
if (cellA < cellB) return -1;
if (cellA === cellB) return 0;
Why is the switch better?
Or even (less explicit, but shorter code): if (cellA === cellB) return 0;
return cellA > cellB ? 1 : -1;Your last version doesn't tell the reader what your intention is at all, and they need to work out what you're trying to do here. It's a lot less readable. Unless you're desperate for those bytes, it'd be better to use the switch statement for this case.
[0]: This gets a little weird in languages like JS where switch statements fall through to the next one if you don't break or return, but generally it still holds true.
if (cellA > cellB) return 1;
if (cellA < cellB) return -1;
if (cellA === cellB) return 0;
throw new Error(); return (cellA === cellB) ? 0 : (cellA > cellB ? 1 : -1); return (cellA > cellB) * 1 + (cellA < cellB) * -1;
More: return Math.sign(cellA - cellB); return (cellA > cellB) - (cellA < cellB); 'ana' > 'Bob'
'2' > '123'
You usually want to clearly define the order or pre-process the strings in some way (trim them, same casing, etc).Or indeed drop the <, > based approach and use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Or: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
return (
(cellA === cellB) ? 0 :
(cellA > cellB) ? 1 :
-1
);
and it's an expression, so i immediately know it won't do any weird control flow. i'd prefer "if/then/else" vs "?/:" but it's not badI find a better indendation style for this is more like
condition
? truthy
: falsyyeah, ternary-if is busted in php :/ (far from the only thing that's busted there though...) i'm actually doing some PHP work right now, and never chain ifs to avoid this exact thing.
The correct is return a<b?-1: (a>b? 1 :0)
var a="a", b=1; a<b ? -1 : (a>b ? 1 : 0); // 0
The switch and if statements would return undefined in these cases. Or others threw an error if none of the conditions matched, that would work too.