Internet Explorer Array.sort Unreliable

What would you expect to be the result of executing the following code?

// Create a medium size array, at least 100 items
var obj = [];
for(var j=0, k=150; j<k; j++) {
    // the value here doesn't matter.
    obj.push('ABCD'+j);
}
 
// Sort the array alphabetically.
obj.sort(function(m,p){
    m=(''+m).toLowerCase();
    p=(''+p).toLowerCase();
 
    if(m > p) return 1;
    if(m < p) return -1;
    return 0;
});

The obj Array should now be sorted, in alphabetical order based on value. BUT, in our best friend Internet Explorer, a Number Expected error may be the result. Don’t be fooled if your test array behaves correctly, it only happens intermittently for arrays of varying size!

So, I whipped up a quick test to check the damage. Iterating over array sizes from 1 to 150, running the Array sort algorithm. The following failures resulted:

Browser Failures *
Internet Explorer 6 4 sizes out of 150
Internet Explorer 7 18 sizes out of 150
Internet Explorer 8 (and Compatibility Mode) 2 sizes out of 150
Internet Explorer 9 (and Compatibility Mode) 0 sizes out of 150 (Fixed!)

* Failures may vary to the specifications of the test machine.

Of course, the Number Expected error is going to result whenever your code doesn’t return a number inside of the function callback. But the problem here is something deeper than simple application code failure. The problem is in JScript itself. Any modification to the sort arguments may result in the Number Expected error.

    m=(''+m).toLowerCase(); // modifies the argument m and is unreliable.

This problem will manifest itself more frequently if you use the Google Closure Compiler, which restructures JavaScript to reuse argument variables if possible, probably to save the 4 character penalty of a “var ” declaration.

Normally, reusing argument variables is a safe practice for primitives, since they are passed by value and not by reference, as is the case in this Array sort example 1. So, what exactly is going on here? One commenter at the Google Closure Compiler bug seems to think that the actual array values are being passed by reference instead of by value. I’m not completely convinced that’s the case.

The Fix

Don’t reuse the argument variables inside of an Array sort function.

// Changing the above example
obj.sort(function(m1,p1){
    var m=(''+m1).toLowerCase(),
        p=(''+p1).toLowerCase();
 
    if(m > p) return 1;
    if(m < p) return -1;
    return 0;
});

Check the source code of the demo file to see the different methods of modifying the arguments that I attempted.

  1. If you want to learn more about passing by value or reference, Jonathan Snook has a nice explanation.

Internet Explorer can’t make you do anything, it can only make you wish you hadn’t.

Updated: Added note about Internet Explorer 9 and its Compatibility View. Looks like it’s fixed!

This entry was posted in JavaScript and tagged , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • Hey! Use the magical power of RSS and Subscribe! Send me a tweet or a pull request!
  • Zach Leatherman is a Professional Front End Engineer. He loves building for the web and has been writing here since 2007. Feel free to stalk his résumé.

    He enjoys spending time with his beautiful wife Traci and their two Great Danes, Roxie and Ella. They also have a cat, a rabbit, goldfish, two poison dart frogs, and usually one or more tarantulas. Read more »

11 Comments

  1. ishtar
    Posted February 24, 2010 at 9:29 pm | Permalink

    Nice write-up. I wonder if your suggestion can be incorporated into the compiled code Google Closure compiler outputs. I noticed that the same solution (of not reassigning the argument variables) fixes the issue in IE for the problem that led me to post that ticket.

  2. Zach Leatherman
    Posted February 24, 2010 at 11:23 pm | Permalink

    I don’t see why they wouldn’t incorporate it, since it is introducing bugs in all versions of Internet Explorer. We’ll see how your report pans out. I’ve submitted a bug before to the Closure Compiler team and it was fixed right away.

  3. Pritesh Patel
    Posted April 24, 2010 at 12:07 pm | Permalink

    Thanks for this. I got my sort function working in IE8 because of this. Otherwise, it was only working in Firefox and Google Chrome.

  4. Valentin Iliescu
    Posted September 5, 2010 at 10:46 am | Permalink

    IE 9 Preview seems to be fine, ran the test several times with no failures.

  5. JKL
    Posted January 3, 2011 at 9:48 pm | Permalink

    Excellent post. In my case this bug caused the first parameter to become undefined. Inspecting it in the script debugger gave a “Variable uses an Automation type not supported in JScript” error. The typeof operator returned “unkown.”

  6. JKL
    Posted January 3, 2011 at 9:52 pm | Permalink

    For the benefit of Google, that last sentence should have been:

    The typeof operator returned “unknown.”

  7. Posted February 21, 2011 at 8:31 pm | Permalink

    GREAT POST
    It just has happened me after having worked ok in my scripts for some time and was quite confussed about the cause. This saved me MANY hours of debugging in IE.
    THANKS !

  8. mort
    Posted March 2, 2011 at 7:33 pm | Permalink

    Thank you. Thank you. Thank you!

  9. Posted June 15, 2011 at 7:33 pm | Permalink

    Really thanks for your article, that issue of IE was driving me crazy.

    What I did to fix it before reading your article was to put the same code in a try/catch statepent but I wasn’t happy with that solution :P

    http://pastebin.com/wCKbuuDV

  10. Marcus
    Posted November 10, 2011 at 9:24 am | Permalink

    Thanks for this. I bumped to the similar problem. I thought surely sort-functions the same in all browser, but should’ve known better.

    In my case the switching
    return (a.label > b.label);
    to
    return (a.label > b.label ? 1 : -1);
    made IE work.

  11. Al
    Posted January 9, 2012 at 11:42 am | Permalink

    Thanks so much for posting this. I was banging my head against the wall before I came across this.

2 Trackbacks

  1. [...] Internet Explorer Array.sort Unreliable – като стана дума за лоши технологии, IE има проблем с Array.sort. [...]

  2. By Array.sort en detalle « Aijoona on August 7, 2011 at 5:25 pm

    [...] Internet Explorer Array.sort Unreliable (Zach Leatherman) [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Comments will be closed on January 8, 2013.