Take a look at this JsFiddle:
var requests = [
$.ajax("http://search.twitter.com/search.json", { data: { q: 'ashishnjain' }, dataType: 'jsonp' })
.done(function() {console.log("request");}),
$.ajax("http://search.twitter.com/search.json", { data: { q: 'ashishnjain' }, dataType: 'jsonp' })
.done(function() {console.log("request");})
];
$.when(requests).done(console.log("alldone"));
The expected output is: request request alldone
, but in reality this prints alldone request request
.
There are actually two bugs in this code (left as an exercise if you enjoy that kind of thing), but ultimately I think this occurs because JavaScript and jQuery are both extremely lenient when given arguments that make no sense whatsoever. In this environment, the "right" thing seems to be "do something or nothing, just do not throw an error!".
Seeing as this code passes JsLint, and has just cost me a couple of hours to debug (the real code was of course a few orders of magnitude more complex), I'm wondering what else I can do to reduce wasting time on such unwarranted leniency. This isn't an isolated example; it seems to happen over and over again. Any suggestions?
It's is actually possible to check types in runtime in Javascript, it's just that being strict is not the preferred style in Javascript. JS hackers like to hang it loose.
Other hackers cope with this though, right? So, rather than blaming the language or jQuery for your long hours spend debugging this problem, I would suggest instead investigating other ways to reduce your debugging efforts.
Here are a couple of suggestions I can think of:
In the case of your more prominent error, the answer can be said in two words: static typing. Static typing doesn't solve every problem but it tears a big chunk out of the work involved in tracking down these subtle failures.
The downsides of static types are not, as missingno claims, anything to do with making programming more difficult or less powerful or anything like that. The biggest problem is that strength of a language's typing system seems to vary inversely with the popularity of the language. Very well typed typed languages like Scala and Haskell are still at the boutique level of acceptance. Java is much more popular, but its type-system is difficult to use and shot full of holes; something similar can be said of C#. The type system of the immensely popular PHP would strike a neutral observer as a deliberate sabotage. Older languages like FORTAN and C don't even try.
I don't know why this is, but I am convinced that the obvious explanation -- people don't like strong typing -- is not correct.
A related problem is that you cannot yet compile any strongly-typed language down to JavaScript. The closest approach is probably GWT.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With