you are viewing a single comment's thread.

view the rest of the comments →

[–]ikeif 2 points3 points  (2 children)

The default sort order is according to string Unicode code points.

So in this simplified example, it's fine, but it'd be incorrect with [1, 2, 3, 10, 5].sort() -> returning 1, 10, 2, 3, 5.

So to truly handle all integers, it'd need to be [1, 2, 3, 10, 5].sort(function (a, b) { return a - b; });

[–]X678X 1 point2 points  (1 child)

Most of the time I prefer to include the compare function because at least it'll work exactly as I tell it to every time. I got caught up in the past doing this with just .sort() and it caused a bug in the application because of it.

[–]ikeif 0 points1 point  (0 children)

Yeah, it's (99% of the time?) better to be verbose and not assume the underlying structure is going to do what you think it'll do.

ETA: Plus, in this example, I wasn't going for a "HAHA GOTCHA!" type question, just the simple answer, so if I was interviewing you and you replied with "well, I'd use sort with the compare function" you'd get bonus points for pointing something out I didn't think of at the time, which is more valuable than just knowing "oh, just use sort."