Why jQuery’s Philosophy is Better

Posted on by

There have been a whole bunch of posts on this blog about the differences in code size between jQuery and Prototype. The basic premise of those posts (which I agree with) is that because of the way jQuery code is structured, all sorts of typical Javascript design patterns are rendered shorter and simpler in the framework when compared with Prototype.

For the longest time, I was a confessed Prototype junkie. I discovered the framework when I started doing Rails work, and for Rails developers, there is very little alternative. Prototype, in all its ugliness, is baked into Rails, and it’s very difficult to give up the productivity gains Rails provides by coding Javascript by hand. Going further on a tangent, that’s why I started working on jQuery on Rails, which aims to allow Rails developers to use jQuery as a drop-in replacement for Prototype.

But back to the purpose of this post, there’s something more fundamentally different about jQuery’s programming sense than just its code size. In fact, the difference in sensibilities is very similar to the difference in sensibilities between Java and Ruby, so it’s ironic that the Rails community has embraced Prototype so completely.

Let’s take a look at some code comparisons. First up, adding some arbitrary HTML after a particular node.

In Prototype:

new Insertion.After('myId', 'Arbitrary HTML');

In jQuery:

$('#myId').after('Arbitrary HTML');

Now, we haven’t done much by way of reducing code clutter (although jQuery’s is cleaner), but there is a fundamental difference in the way that Prototype and jQuery each approach the problem.

Prototype creates a series of monolithic classes that each encapsulate some functionality. Developers then pass in an id, and some other parameters, and the class does what it’s supposed to do. Very much like the Java way of encapsulating functionality (like the Math class, for instance). NOTE: That’s not to say that Java couldn’t do things this way.

jQuery approaches the problem in a fundamentally different way. It sees sets of HTML nodes as objects to pass messages to (more like the traditional Ruby way). So instead of having a separate class that adds text after an HTML node, jQuery glues the functionality onto the jQuery object, which is returned by the $ function. By contrast, Prototype’s $ function returns a vanilla DOM node.

Prototype attempted to achieve similar functionality with its $$ method added in the latest RC of the framework, but there’s a fundamental difference. While Prototype’s $$ returns an array of DOM Elements, jQuery’s $ is the fundamental underpinning of the entire framework. Virtually all jQuery functions bind to the jQuery object, which is returned by the $ method.
The benefits of the jQuery way are highly visible:

  • Chainability. Because jQuery objects have functionality glued onto them, they return other jQuery objects, which the developer can then pass additional messages to. The trivial example on the jQuery website is $(“p.surprise”).addClass(“ohmy”).show(“slow”);
  • Use of CSS selectors and XPath operators. Because jQuery passes messages to objects, it can (and has) implement additional selector functionality into the $ method. The methods that are glued onto jQuery objects just see an array-like object that holds a series of DOM elements. It doesn’t care how we got them. So plugin developers can add additional parsers into the $ method, or glue additional functions onto the jQuery object rather easily.
  • Which brings us to plugin development. The jQuery way is very conducive to plugin development. It’s quite easy to add functionality that takes advantage of the jQuery object, and jQuery plugins are usually much shorter than their counterparts. jQuery Plugins
  • Automatic looping. jQuery methods are required to automatically loop through all DOM elements in the array, and apply the desired method. So $(expression).after(‘some HTML’) transparently adds the HTML after every single element returned by the expression. $(‘p’).after(‘some HTML’) will add ‘some HTML’ after every <p> on the page, for instance. Personally, I find the elimination of iteration in my code (in most cases) to be one of the top practical, day-to-day benefits of using jQuery.
  • Builds on itself. As jQuery has matured, it’s become easier to build plugins on top of the existing architecture. Because all jQuery functions automatically loop, using existing jQuery functions means that annoying iteration is all but gone.

There’s more, but the thread that runs through all of the benefits comes out of the very meticulous way that John Resig has made the jQuery object/array accept passed messages, rather than build various monolithic functionality blocks, each of which must be built from scratch.

Some other examples:
AJAX Updater in Prototype:

new Ajax.Updater('placeholder', url, { method: 'get', parameters: par });

AJAX Updater In jQuery:

$('#placeholder').load(url + par);

Note: This example doesn’t deal with the obvious iteration benefits we get if we wanted to load the response into every <p> object, for instance.

Adding a class to an element in Prototype:

Element.addClassName('element', 'className');

Adding a class to an element in jQuery:

$('#element').addClass('className');

Adding a class to a group of elements in Prototype:

$$('.element').each(function(node) {
Element.addClassName(node, 'className');
}

Adding a class to a group of elements in jQuery:

$('.element').addClass('className');

That last one is the clearest example of the difference in methodology. Because jQuery is passing messages to jQuery objects, the code is barely changed. jQuery doesn’t care that we’re now adding a class to a group of objects instead of one object; the underlying code is the same (add the class to the set of elements in the object). Prototype, on the other hand, requires an iterator.

And as your code becomes more complex, jQuery’s scales easily, while nested loops become the norm in frameworks like Prototype.

[UPDATE] An astute reader (Mislav) pointed out that Prototype does indeed do just a bit of what jQuery does. Prototype seems to bind the Element class to DOM Elements, allowing things like $(‘myElement’).hide(), and such. However, it only applies to the Element module, and seems to only work on single DOM elements. Binding the Elements module is cool, but it’s more an afterthought than the way jQuery makes it a fundamental design decision.

98 thoughts on “Why jQuery’s Philosophy is Better

  1. Pingback: Какой JS-фреймворк выбрать? » Wake Up!

  2. Pingback: Jquery vs Prototype na prática at Webpoint - Weblosofia com CSS, Jquery, Javascript, Ajax, PHP etc.

  3. Pingback: Design By Tim » Blog Archive » jQuery for the non-visually impared

  4. Pingback: The Five JavaScript Libraries - Scatterism

  5. Pingback: My Cup of Java - Today’s Top Blog Posts on Java - Powered by SocialRank

  6. Pingback: Phil Rathe.com » jQuery + Rails ( Part 1 )

  7. Pingback: Phil Rathe.com » jQuery + Rails ( Part 1 )

  8. Hi, I´m new to this stuff but I guess it´s not only prototype that makes it interesting for ruby but also scriptaculous which needs prototype and I heard, prototype enlarges the capabilities of javascript, does jquery provide this additional funct. too?

  9. Pingback: Prototype en JQuery, ‘t vervolg « CoochieHoochieMan

  10. jQuery is awesome for most of my projects. There are others where I use prototype but its all about using the best tool for what needs to be done.

    To those who are complaining, you can *use whatever you want*. If you cant then learn how to deal with more than one framework and improve your coding skills, thats your problem. Also, like some people have posted… not using a framework because you disagree with the community behind it? Really? I bet that goes over real well when it comes to actually doing work, choosing something for a job not because its right but because its “community” is better.

    PS. I hate javascript. Freakin ajax hippies.

  11. AAR Group: áóõãàëòåðñêèé ó÷åò, êàëåíäàðü áóõãàëòåðà, ïðîèçâîäñòâåííûé êàëåíäàðü è áóõãàëòåðñêàÿ ôèíàíñîâàÿ îò÷¸òíîñòü, êàëåíäàðü áóõãàëòåðà 2008, àóäèò, êàäðîâûé êîíñàëòèíã, àóäèò, àóäèò áóõãàëòåðñêèé ó÷åò è êàëåíäàðü áóõãàëòåðà ñàéò http://www.aargroup.ru

  12. CFO Russia – áëîãè ,à òàêæå ýòî ïðîñòðàíñòâî äëÿ íåçàâèñèìîãî îáùåíèÿ òîï-ìåíåäæåðîâ íà òåìû è âñå äëÿ îáùåíèÿ ôèíàíñîâûõ äèðåêòîðîâ ,à òàêæå ñâÿçàííûå ñ óïðàâëåíèåì è ôèíàíñàìè, è ïëîùàäêà äëÿ îáùåíèÿ ôèíàíñîâûõ äèðåêòîðîâ. Ñàéò http://www.cfo-russia.r

  13. ÖÍÈÝÏ ýòî âíóòðåííèå àóäèòû è ôèíàíñîâûé àíàëèç è óïðàâëåíèå áèçíåñ ïðîöåññàìè è ìîäåëèðîâàíèå áèçíåñ ïðîöåññîâ è íàó÷íî èññëåäîâàòåëüñêèå ðàáîòû, ïîâûøåíèå êâàëèôèêàöèè è áóõãàëòåðñêèé ó÷åò, ñèñòåìà ìåíåäæìåíòà êà÷åñòâà, ñàéò http://www.effcom.ru.

  14. Ôåìèäà-Àóäèò ýòî: àíàëèç áóõãàëòåðñêîé îò÷åòíîñòè, due diligence, àíàëèç áóõãàëòåðñêîé îò÷åòíîñòè, à òàêæå àíàëèç áóõãàëòåðñêîé îò÷åòíîñòè, à òàêæå due diligence è due diligence, à òàêæå îïòèìèçàöèè íàëîãîîáëîæåíèÿ, ñàéò http://www.femida-audit.com

  15. Ôåìèäà-Àóäèò ýòî: îïòèìèçàöèè íàëîãîîáëîæåíèÿ, à òàêæå óñëóãè âåäåíèÿ áóõãàëòåðñêîãî ó÷åòà è îöåíêà ïàêåòîâ àêöèé, à òàêæå àóäèò îò÷åòíîñòè è îöåíêà ïàêåòîâ àêöèé è àóäèò îò÷åòíîñòè, à òàêæå àóäèò êðåäèòíûõ îðãàíèçàöèé, ñàéò http://www.femida-audit.com

  16. AAR Group: áóõãàëòåðñêèé ó÷åò, ðàçðàáîòêà ñòðàòåãèè è óñëóãè áóõãàëòåðñêîãî ó÷åòà, áóõãàëòåðñêàÿ ôèíàíñîâàÿ îò÷¸òíîñòü è áóõãàëòåðñêèå óñëóãè, îðãàíèçàöèÿ áèçíåñà è áèçíåñ ïëàí îðãàíèçàöèè è áóõãàëòåðñêàÿ ôèíàíñîâàÿ îò÷¸òíîñòü ñàéò http://www.aargroup.ru

  17. Êàðòà Ìîñêâû, ïèðàìèäû è ïîèñêîâûé, ôîòî è êàðòà Åãèïåò, äîìà è èíòåðàêòèâíàÿ êàðòà, map Moscow è breadth of Moscow, satellite card è êàðòà Èñïàíèè è êîñìîäðîìû, ïèðàìèäû è êàðòà ìîñêîâñêîé îáëàñòè è êîîðäèíàòû ìåñòíîñòè, íà ñàéòå SmMoscow.Narod.Ru

  18. Pingback: JQuery vs. Prototype | Phine Solutions

  19. Ïåðåîôîðìëåíèå àâòîìîáèëåé, ìîòîöèêëîâ, íîìåðíûõ àãðåãàòîâ, ñïåöòåõíèêè äëÿ ôèçè÷åñêèõ è þðèäè÷åñêèõ ëèö. Áåçíàëè÷íûé, íàëè÷íûé ðàñ÷åò, ïðåäîñòàâëÿþòñÿ âñå äîêóìåíòû äëÿ áóõãàëòåðèè, êàññîâûé ÷åê, ñ÷åò ôàêòóðà.

  20. Pingback: What Makes jQuery a Good Choice?

  21. CFO Ðîññèÿ – ñòàòüè, êàê îñóùåñòâëÿëè ðåîðãàíèçàöèþ è áëîãè è êàê îñóùåñòâëÿëè ðåîðãàíèçàöèþ è ñòàòüè ,à òàêæå ñâÿçàííûå ñ óïðàâëåíèåì è ôèíàíñàìè, ,à òàêæå ïðîõîäèëè îáó÷åíèå è âñå äëÿ îáùåíèÿ ôèíàíñîâûõ äèðåêòîðîâ. Ñàéò http://www.cfo-russia.r

  22. Ìåáåëü èç ìàññèâà, òåëåôîííàÿ áóäêà, êàáèíåòû èç ìàññèâà ,à òàêæå òåëåôîííàÿ áóäêà è âèííûé ïîãðåá, ìåáåëü èç äåðåâà, ìåáåëü èç ìàññèâà ,à òàêæå âèííûå øêàôû ,à òàêæå èçãîòîâëåíèå ìåáåëè ,à òàêæå èçãîòîâëåíèå ìåáåëè íà çàêàç. Ñàéò http://www.r-wood.ru

  23. Ñèãàðíûé ñàëîí ,à òàêæå ñèãàðíûé ñàëîí, ñèãàðíûé ñàëîí ,à òàêæå èíòåðüåðû èç äåðåâà ,à òàêæå õüþìèäîðû è êàáèíåòû èç ìàññèâà ,à òàêæå òåëåôîííàÿ áóäêà, ìåáåëü èç ìàññèâà è õüþìèäîðû ,à òàêæå äèçàéí ìåáåëè ,à òàêæå õðàíåíèå âèíà. Ñàéò http://www.r-wood.ru

  24. ÖÍÈÝÏ ýòî ôèíàíñîâûé àíàëèç ïðåäïðèÿòèÿ è ôèíàíñîâî õîçÿéñòâåííûé àíàëèç ïðåäïðèÿòèÿ è áóõãàëòåðñêàÿ ôèíàíñîâàÿ îò÷¸òíîñòü, àíàëèç ôèíàíñîâîé äåÿòåëüíîñòè è öåíòð ïîâûøåíèÿ êâàëèôèêàöèè, àíàëèç ôèíàíñîâîãî ñîñòîÿíèÿ, ñàéò http://www.effcom.ru.

  25. Êîìèññèîííûé ìàãàçèí îêàçûâàåò óñëóãè ïî îôîðìëåíèþ êóïëè ïðîäàæè àâòîìîáèëÿ ïî ñïðàâêå ñ÷åò îáÿçàòåëüíîå ñòðàõîâàíèå ãðàæäàíñêîé îòâåòñòâåííîñòè ÎÑÀÃÎ ðàñ÷¸ò íà êàëüêóëÿòîðå, Àâòîêàñêî. Êîíñóëüòàöèè ïî âîïðîñàì îôîðìëåíèÿ.

  26. Бегун не убежал от Гугла и Web-мастера радуются успехам Гугла, а также Google шагает по РУнету, а также Google покупает Бегун, а также Бегун скоро исчезнет, кто следующий? и Google шагает по РУнету и В РУнете дав играка: Google и Yandex

  27. Íà ñàéòå âû ìîæåòå âûáðàòü ñåáå áðèòàíñêîãî êîòåíêà ïî ôîòîãðàôèè, óçíàòü, êàê ïðàâèëüíî óõàæèâàòü çà íèì, êîãäà äåëàòü ïðèâèâêè, ÷åì êîðìèòü, ïîäîáðàòü åìó èìÿ – êëè÷êó. Òàêæå ìîæåòå îçíàêîìèòüñÿ ñ èñòîðèåé ïðîèñõîæäåíèÿ øîòëàíäñêèõ êîøåê.

  28. Pingback: A small question - eXceem

  29. Pingback: A small question - eXceem

  30. гаап, а также гаап, мсфо, а также стандарты мсфо и международные стандарты отчетности, а также gaap, международные стандарты отчетности и международные стандарты бухгалтерского учета, международные стандарты, стандарты мсфо на сайте femida-audit

  31. Prosperity Media это поный комплекс услуг создание концепции дизайна, корпоративные издания, разработка интернет-сайтов и корпоративной прессы и Prosperity Media – PR, создание сайтов-визиток и издание корпоративной прессы сайт Prosperity-Media Ru

  32. Что мы предлагаем практические занятия по математике, а также курсы в Долгопродном, а также курсы для учащихся 11 классов и в помощь школьнику, а также теория поля, курсы по физике, а также сборник задач по физике сайт Potential.Org.Ru

  33. Õàé, áûëî î÷åíüïîçíàâàòåëüíî àâñ ïî÷èòàòü. òîëüêî âîò îäíîíå î÷åíü õîðîøî Ñïàìåðû äîñòàëè, ó ìåíÿ ó ñàìîãî åñòü ñàéò òàê è íà ïðåìîäåðàöèþ ñòàâèòü âñå ñîîáùåíèÿíå äåëî, à âîò êàïò÷ó íèêàê íå ìîãó óñòàíîâèòü, íå ïîëó÷àåòñÿ…

  34. Заметил такую тенденцию, что в блогах появилось много не адекватных комментариев, не могу понять, это что кто то спамит так? А зачем, чтоб падлу комуто сделать))) Имхо глупо…

  35. Здравствуй, чесно сказать не ожидал от вас такого бреда))) позырил твои предыдущие записи, они были более содержательными. Прости за прямоту=)

  36. Mehdi_A on said:

    what about the compatibility of jQuery and/or Prototype with some server-side frameworks(like JSF + Richfaces, which are my goal).
    I’m researching about the compatibility of them and also the possibility of replacing the Ajax-based server-side libraries with a client-side.

  37. 3 ноября 2008 года в бизнес-центре «Холидей Инн Сущевский» пройдет конференция на тему: «Система управленческого учета: разработка и применение». http://www.cfo-russia.ru

  38. Учебный центр Фемида–Аудит – подготовка к экзамену по ДипИФР ACCA подробнее femida-audit.com

  39. Информационный портал и площадка для финансовых директоров. Блоги, статьи, форум. Сайт http://www.cfo-russia.ru – это общение без посредников.

  40. Спасибо за новость автору, ждём новых топиков.

  41. Pingback: the time has come: converting Prototype into jQuery