en_GB@blog

Open Source and Other Things

Tag Archives: WTF

Reasons to hate Javascript (2)

Javascript arrays are probably reason enough to keep yourself away from the language, but anyway: sort compares strings by default and ordering an array of numbers will result in something unexpected, unless you provide your own comparison function:

// open firebug console to see the output
var arry = [ 42, 13, 6, 9, 12, 58, 1 ];

// by default it treats the numbers as strings
console.log(arry.sort()) // [1, 12, 13, 42, 58, 6, 9]

// providing a comparison function
console.log(arry.sort(function (a,b) {
        if (a>b) {
                return 1;
        } else {
                if (a<b) {
                        return -1;      
                } else {
                        return 0;       
                }
        }
        // or return a-b
})); // [1, 6, 9, 12, 13, 42, 58]

I don’t know if we could include this in the Javascript arrays are a non-sense box, but it’s definitely an odd behaviour.

Reasons to hate Javascript

The length property in an array:

// check the output on firebug console
var arry = [];

console.log(arry.length); // 0

arry[100] = 'one element';
console.log(arry.length); // 101

for(idx in arry) {
	console.log(arry[idx]);
}
// one element

Yes, the array has only one element and length is showing the largest integer property name in the array, plus one.

Follow

Get every new post delivered to your Inbox.