40

I'm struggling to find a way of writing good JavaScript code that would be efficient, widely accepted by other developers and not very ugly.

Until recently, what I used were just literal objects and bits of jQuery but after reading Douglas Crockford's "JavaScript: The Good Parts" I now fully realize that there's more to JavaScript than AJAX, DOM modifications and simple animation.

The problem is that JavaScript seems not much standarized. The amount of OOP/inheritance patterns available overwhelms me. I'm not used to every framework/library providing its own impementation of inheritance. I also don't want to make a wrong decision regarding such things because this would mean rewriting all the code in case of some problems.

So what I'm looking for are existing open source web applications that use JavaScript heavily, if possible on the client side, to see what patterns are used in real projects. I would like to see the code of web applications, not frameworks or libraries. I don't mind though if those web apps are based on some framework (and if it's Dojo or RequireJS it'll be even better because I'm using them ;)

Juliusz Gonera
  • 4,658
  • 5
  • 32
  • 35
  • 3
    It's Javascript, It's all client side. You don't need open source projects to view their Java Script. You can just view source and that's it. – Rob Jun 02 '11 at 12:02
  • 9
    @Rob, what you're saying was true 5-10 years ago. First of all, it's not all client side now, I guess you haven't heard at all about [node.js](http://nodejs.org/), [Rhino](http://www.mozilla.org/rhino/) and other similar projects. People actually write _servers_ in JS nowadays. Secondly, well-designed web applications optimize (uglify) their client-side JavaScript code. Such optimized code is unreadable and the process itself is pretty much irreversible (see [this](http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js); among many things, variables get meaningless short names). – Juliusz Gonera Jun 02 '11 at 14:27
  • @Juliusz I take your point, although Jquery is minified there is also a non minified version that in the words of the jquery website "The code, itself, is written rather cleanly -- in an attempt to be self-documenting." Maybe it's not as easy to find than I thought. I have never had a problem finding a piece of javascript when I see something I like. But then maybe things are changing. – Rob Jun 02 '11 at 15:09
  • 1
    @Arend, after working a lot with Python, I've got more used to "There should be one-- and preferably only one --obvious way to do it" ([PEP 20](http://www.python.org/dev/peps/pep-0020/)) and that's why JS seems so confusing. I'm ready to accept the fact that JS is more flexible (although sometimes this flexibility is a result of being incomplete), but I would like to see how professional JS programmers code. I can find a lot of JS code on Github, but the vast majority are libraries or plugins. I would like to see a complete web app. – Juliusz Gonera Jun 02 '11 at 15:15
  • 2
    @Rob, maybe I've given a bad example. I know that there's a non-minified version of jQuery, but I specifically said that I want to see _web apps_ code, not libraries or frameworks. Where can I find non-minified version of [StackOverflow's JS](http://cdn.sstatic.net/js/stub.js) or better, GMail's JS? Nowhere, because it's not open source. – Juliusz Gonera Jun 02 '11 at 15:19
  • @Juliusz You're absolutely right.Like I said, I do take your point. I hope someone does answer this question and points you in the right direction. The thing is I can't see their being a large open source implementation of Javascript that isn't a framework or platform. Anyway, enough of me wasting your time. Good luck! – Rob Jun 02 '11 at 15:29
  • 1
    @Juliusz: but still you may study the closure library, which contains many of the wisdoms, patterns of 'real' applications (and also really seperate JS applications, editors, etc.). It's save to assume that big applications are constructed in a similar manner. Perhaps also this document is of use to you? http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml – Arend Jun 02 '11 at 16:12
  • @Arend, thanks for the link, I'll add it to my JS bookmarks. I studied a bit of Dojo's code, but it seems to be in a transitional stage because its developers are going to change the loader they're using. It results in weird things, like using `dojo.declare("dijit.layout.ContentPane"...` which clobbers the global namespace just to return it later as an AMD module. JavaScript is changing fast nowadays, but libraries/frameworks need to maintain compatibility with their previous versions. This may result in a lot of weird/ugly code. A web app and its code are not constrained in such way. – Juliusz Gonera Jun 02 '11 at 16:45
  • I have worked with JavaScript for a few years now. I would say that your question is very valid (JavaScript has too many ways to do things). But in the end I think that you should go with what works for you. Find a library that you like, use modules for encapsulation, understand you sites "onload waterfall" and you might want to look into custom events. And with most modern browsers JavaScript performance is not a problem. – babsher Jun 09 '11 at 19:13

8 Answers8

7

What I always recommend to anyone who is interested in this kind of thing is: STICK TO WHAT YOUR TEAM DOES. If they use camelCase for methods, you use it. If they use snake_case for variables, you do it. If your team prefers spaces over tabs; use them.

Never go into a stablished team with standardized style changing things because it looks better unless it's causing heavy problems.

If you're not working on a team and you're interested on using a coding style; then use the style of the libraries you use the most.

Organization wise, Closure is the best.. but to me somehow it feels like I'm reading JAVA instead of javascript. Go figure.

Aaron Yodaiken
  • 19,163
  • 32
  • 103
  • 184
Ferrerira
  • 91
  • 2
  • These are all browser specific examples. Maybe you could include a reference to Node JS or common JS. – babsher Jun 03 '11 at 15:52
  • 3
    First of all, I'm not working in a team. What you said is very true, but has little to do with my question. I don't have problems with naming conventions. I'm not sure how to structure my code in JS, both object/class-wise and file-wise. – Juliusz Gonera Jun 04 '11 at 12:35
5

Yep. There are a few JavaScript gurus that have written alot about how to write JavaScript, about prototype based OOP with JavaScript, even about how indenting and naming variables should be done.

However, if you are looking for a large implementation of JavaScript to study as an example, I would look for HTML5 game implementations. It's practically guaranteed that you will find a large enough, well written example that is not minified.

filipe
  • 1,641
  • 1
  • 9
  • 8
4

If you are interested in JavaScript standards I would check out commonJS. They have a lot of good ideas about how JavaScript should be done.

BravoJS is a good module implementation for the browser.

As for examples jQuery's source code was mentioned in the comments. jQuery does a good job but it is I would also check out Narwhal JS for examples of how things should be done.

Here is a good free design patterns book that I found helpful Essential JavaScript And jQuery Design Patterns.

You wont find one solution to your problem and that is how JavaScript is designed. I would recommended experimenting. I find that Douglas Crockford has a lot of great ideas but that does not mean you have to follow him to the letter.

babsher
  • 1,016
  • 2
  • 8
  • 11
  • 1
    CommonJS has recommendations on how to write a API for a standard library not how to write application code. – Raynos Jun 04 '11 at 19:02
  • There are some examples of how to use there specs. I think that commonJS is really the way that JavaScript is moving, especially with the module and promise specs. Both of these are in heavy use in the JavaScript world. – babsher Jun 04 '11 at 23:04
  • I'm tempted to say many people are taking ideas from commonJS but commonJS itself will never become a standard API in the js world. – Raynos Jun 04 '11 at 23:21
2

A good project is : http://impactjs.com/ A good reading is : http://addyosmani.com/blog/essentialjsdesignpatterns/

standup75
  • 4,734
  • 6
  • 28
  • 49
  • This is something interesting. It seems their classes have no encapsulation though, but maybe this is the way to go to avoid nesting things in closures. Python does well without encapsulation, so why not. – Juliusz Gonera Jun 04 '11 at 12:33
  • 2
    But impact is not open source! You have to pay for it :( – Raynos Jun 04 '11 at 19:01
  • If you want encapsulation I would use BravoJS. http://code.google.com/p/bravojs/ It is a commonJS module implementation for the browser. It is nice to not have all your variables in the global scope. – babsher Jun 04 '11 at 23:01
  • @Raynos, I've taken a look at [Drop source](http://impactjs.com/documentation/drop-source-code) which gave some idea of how they organize classes, but you're right, it's not open source. – Juliusz Gonera Jun 05 '11 at 09:52
  • @user673289, any advantages of BravoJS over [RequireJS](http://requirejs.org/)? RequireJS seems more popular and has good documentation. – Juliusz Gonera Jun 05 '11 at 09:53
  • @Juliusz There may be a difference but the only reason why I choose BravoJS is because it was really easy to get started. I did not need all the features that RequireJS had. – babsher Jun 05 '11 at 18:53
2

Great question. I couldn't find one example of a well written object oriented open source application. Tiny MCE was so-so, but I wouldn't consider it well written: http://www.tinymce.com/

However, I have written clean, well factored object oriented javascript at work. It's proprietary so I can't share it, but I can explain what worked for me to learn how to do that:

1) Read the mozilla javascript object oriented programming tutorial. Their explanation of javascript inheritance is exactly what google closure uses. Personally I think what Crockford calls pseudo classical is easiest to read and maintain since 4 of the 5 other programming languages I know use classes (java, c#, python, and php. perl's the oddball here with no classes either).

https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript

2) Read the book 'Object Oriented Javascript' by Stoyan Stefanov.

3) Take an existing procedural javascript code base and refactor it to objects. Use the tips in 'Clean Code' by Robert C. Martin as they apply to any programming language.

4) Structure your code so it has many different files similar to how you'd use classes in a language with classes.

5) Implement dependency injection without an IOC container by creating all your objects at a top level and feeding them down into the objects that depend on them.

There's a lot more, but hopefully this is a helpful start.

Here is what I feel is the correct way to implement inheritance in javascript. this is from the google closure library:

goog.inherits = function(childCtor, parentCtor) {
  /** @constructor */
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  childCtor.prototype.constructor = childCtor;
};
davidjnelson
  • 1,111
  • 12
  • 22
0

A kind person in irc suggested this eBook and I found it verry helpful.

Learning JavaScript Design Patterns

A book by Addy Osmani

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Bronwen
  • 36
  • 4
0

There are several ways to learn how to write good JS code.

You can read books. The best one about organization of JS code and about common patterns including inheritance is JavaScript Patterns by Stoyan Stefanov.

Another good way to learn is just look through the excellent code of other developers and using it. The best library I've seen from the point of code organization and using of patterns is Google Closure Library. It is used internally by Google in the RIA like Gmail Google Docs.

bjornd
  • 22,397
  • 4
  • 57
  • 73
0

Coincidentally, today on SlashDot there is a review of the 6th edition of Javascript: The Definitive Guide, which the reviewer there says "retains its crown as the ultimate reference resource for JavaScript programmers." It's 1,100 pages.

Yes, this isn't the sample app you were seeking, but the book does have a lot of examples and advice about best practices.

DOK
  • 32,337
  • 7
  • 60
  • 92