hsy0
hsy0

Reputation: 139

Why does ExtJS want to test if browser supports sorting?

I'am a javascript newbie, here is code from ExtJS which confuses me:

supportsSort = (function() {
    var a = [1,2,3,4,5].sort(function(){ return 0; });
    return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
}()),

Is someone can tell me why ExtJS want to do this test?

It is better to attach some examples code.

Upvotes: 6

Views: 256

Answers (2)

kuldarim
kuldarim

Reputation: 1106

I think this test is needed to check if browser supports this feature or not.

As this is discussed in this post or in this link you can find Array.prototype.sort([comparator]). There is shown that not all browsers versions supports sort function.

These days there isn't browser which does not support this function (i'm talking about latests versions). But in case if Ext Js is used to develop for earlier versions it becomes needed.

Upvotes: 0

Emissary
Emissary

Reputation: 10148

Hesitant to post this as the answer as I'm admittedly just taking an educated guess but according to MDN, the browser-compatibility for Array.sort is listed as ECMAScript5 and "yes" for everything (as opposed to listing actual version numbers) - leaving a test for actual support more or less redundant.

The variable name is probably a little bit miss-leading though because if you actually follow what it's doing, the function that is passed to sort is just returning 0; typically you might return 1 or -1 depending on your comparison conditions in order to manipulate the order of the array - so by doing this the expected result is that the order of the array remains unchanged.

The return statement is just a chain of boolean checks as to whether the array is still in the same order as it was initially. Arguably then this supportsSort flag is there to check whether or not the browser/Javascript's implementation of the sort function is in fact a stable algorithm.

Upvotes: 2

Related Questions