The Magic Beyond JavaScript Types

Thu, Dec 6, 2012 2-minute read

I am recently working with JavaScript and I can only have mixed feelings about it.

I like a lot its libraries, especially jQuery and d3, that make it possible to build amazing things with a very little effort.

Besides these good things I cannot stand part of JavaScript syntax and some weird behavior due to its dynamic nature.

Things like the lambda functions syntax (function(...){return ...;}) always make me want to switch to another language. Especially considering how often you need to define a lambda function in JavaScript, they definitely should have come up with a more concise syntax.

Syntax is not even the worst part of JavaScript to me. I prefer strongly typed languages like Scala and I cant get how people can code without the help of a compiler and a type system spotting nasty errors for them.

Dynamic typing lead to other extremely bad design decision. As an example, try to guess what is the outcome of this operation [1,2,10].sort(). It should be straightforward. It is an array of integer literals, what could possibly go wrong?

Actually, you are assuming that sort is somehow aware of the type of the content of the array, which is not the case. So, unless you provide an ordering function, everything falls back to lexicographic ordering. Not the most natural ordering for integers, isn’t it?

With the array I used in the example the result is [1,10,2] and I bet you expected it to be something else when you invoked the function.

If you are wondering what you should do to get a more natural ordering have a look at this StackOverflow question and answer. The answer suggests to use this function:

function sortNumber(a,b) {
    return a - b;
}

That of course it works well only if you are sure you are dealing with numbers. Because, remember, you cannot constrain the type of the content of the array so you either have to trust the callee (And it’s always a bad decision) or check that the input type is what you expected.

Does it seem easy to check whether an object is a number or not?

Well, it turns out that number validation is hard. You either have to rely on an external library, such as jQuery, or you need to do something dirty like this:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}