Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

  • Blog Navigation
JavaScript disappoints yet again: sorting an array of numbers

We were writing a spec yesterday where we had a method that was returning an array of numbers in no particular order, and we wanted to verify its output. It went something like:

expect([1, 2, 3, 10, 25]);

The error message from Jasmine was something like “expected [1, 10, 2, 25, 3] to equal [1, 2, 3, 10, 25]”.

I couldn’t believe it. I wanted to sort an array of numbers, and JavaScript decided it would do me a favor and cast them all to strings first.

The workaround is simple: Mozilla recommends just passing a comparison function to sort:

expect(, b) {
    return a-b;
})).toEqual([1, 2, 3, 10, 25]);

When you’re working in JavaScript everyday, you learn to expect the unexpected to some extent, but even this one threw me off.

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *

Share This