Hacker Newsnew | comments | show | ask | jobs | submit login
Ask HN: Learning to write good JavaScript
163 points by rcknight 956 days ago | 49 comments
The majority of my programming since university has been in the .net space... but am being increasingly required to deal with JavaScript day-to-day and would like to learn more. Initially this will mostly be for web development, but I've been meaning to play with node for a long time as well.

I am comfortable enough with the basic syntax etc, so not looking for absolute beginners stuff, but I would love some recommendations of resources that teach about real world use of the language ... common patterns & anti-patterns, typical coding style etc. A nice book or two would be ideal, but online resources are fine too!

Basically I don't just want to write JavaScript, I want to write good JavaScript.




Check out the code in the open source project fabric.js http://fabricjs.com/ . It's written by Juriy Zaytsev who was a maintainer for prototype.js. I find the code useful for learning advanced object oriented JavaScript because:

1) It's self contained. No dependencies on third party OO libraries or frameworks.

2) The code is very readable.

3) It's a canvas library, so it's fun to work with if you're into graphics and visualizations.

4) You'll learn a lot about how many JS projects are built, documented, and tested, if you get it to build and the tests running on node.js.

Here is what I would do:

1) Check out the project and get it building.

2) Read all the files in the util folder. You'll see a lot of methods added to Object and Array.

3) Take a look at lang_class.js: https://github.com/kangax/fabric.js/blob/master/src/util/lan... This is how he does OO JS. It's very similar to John Resig's OO classes: http://ejohn.org/blog/simple-javascript-inheritance/ and somewhat different to prototype's classes: https://github.com/sstephenson/prototype/blob/master/src/pro...

4) Then take a look at the base class: https://github.com/kangax/fabric.js/blob/master/src/object.c... and an inherited class: https://github.com/kangax/fabric.js/blob/master/src/line.cla...

5) Search for instances of the "bind" method, and see how they're used.

Of course, as you're doing all this, you'll need to experiment with simple language constructs in your browser's console to test what you think you know, and you'll want to read some chapters from a thorough JS book like, JavaScript the Definitive Guide http://shop.oreilly.com/product/9780596805531.do

Finally, this is just a personal opinion, but I don't like Crokford's chapter on OO JS. I just don't think it presents your options well. If you decide to write a large project in JS using OO techniques, I think you'd be better off utilizing an OO library, compiler, or framework like TypeScript, Google Closure, Prototype or CoffeeScript, than you would charging forward armed with Crokford's chapter on OO.

-----


I second the recommendation for fabric js. It's the first JS library I ever used, since I was playing with canvas to begin with. The code is definitely very readable and the author is super responsive on stackoverflow and Google+. His documentation and examples are excellent.

-----


Thanks for the recommendation! It will definitely be useful to dig through a great JS codebase alongside all the excellent reading suggested here!

-----


Some good tips and resources there, I should check them out more in detail too. Thanks!

-----


You can learn a ton about the language itself by reading. A good place to start is this collection of free online resources.

http://jsbooks.revolunet.com/

My favorites from this site are as follows: http://eloquentjavascript.net/contents.html http://bonsaiden.github.com/JavaScript-Garden/ http://www.addyosmani.com/resources/essentialjsdesignpattern... http://jstherightway.com/

Mozilla has excellent JavaScript material: https://developer.mozilla.org/en-US/docs/JavaScript/Guide https://developer.mozilla.org/en-US/docs/JavaScript/Referenc...

As far as print goes, you'll want these books in your reading list:

JavaScript: The Good Parts by Douglas Crockford Secrets of the JavaScript Ninga by John Resig

-----


Every good resource that I can think of has already been listed by @dutchrapley, with the exception of 1 (so he gets my vote :D) - Once you finish reading 'The Good Parts' and 'JavaScript Ninja' take a look at 'JavaScript Patterns' by Stoyan Stefanov [www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752/]

On a related note, there was some interesting discussion right here on HN with regards to Addy Osmani's JS Patterns eBook - http://news.ycombinator.com/item?id=2762888

-----


I'll second 'Javascript Patterns', and add 'Maintainable Javascript' by Nicholas Zachas [http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zak...]

-----


These are some good resources that will teach you how to write good javascript. Having an understanding of the core language rather than using frameworks is a great start:

Eloquent JavaScript: http://eloquentjavascript.net/contents.html

Learning JavaScript Design Patterns: http://www.addyosmani.com/resources/essentialjsdesignpattern...

JS The Right Way: http://jstherightway.com/

Learning Advanced JavaScript: http://ejohn.org/apps/learn/

Ask HN: JavaScript Dev Tools: http://news.ycombinator.com/item?id=3550998

MVC Architecture for JS: http://michaux.ca/articles/mvc-architecture-for-javascript-a...

Large-Scale JS Application Architecture: http://addyosmani.com/largescalejavascript/

Mozilla Developer Network - Intro to OO JS: https://developer.mozilla.org/en-US/docs/JavaScript/Introduc...

-----


Eloquent Javascript is just awesome... learned a lot from it.

-----


Read everything that Crockford has said about Javascript: http://javascript.crockford.com/ and especially don't miss his videos.

-----


I'm going to second this. Crockford's book Javascript the good parts helped me a ton when getting up to speed in javascript. Ended up building a timecard javascript application for mobile.

I'll also recommend spending a little time with javascript before jumping into jQuery. learning how things are scoped is important.

-----


JavasScript is an API language that allows you to write embedded programs to interact with the environment. The environment can be low level APIs such as browser DOM, WebKit library or Node.js process, or high level abstractions such as jQuery, Backbone, d3.js, etc.

GOOD JavaScript is the code that plays nicely with its environment. There is no strict best practice for every situation. You have to learn the language of your neighborhood.

-----


Since you are familiar with .net, I recommend studying typescript http://www.typescriptlang.org/

You'll learn a lot from watching their tutorials and how the code is converted to javascript.

-----


I have had a brief look at typescript, it does look interesting!

However I think I would rather get a strong handle on vanilla JavaScript before I start looking at things like Coffeescript/Typescript.

-----


I recommend not studying fancy stuff since you understand its root. Learn vanilla javascript first :)

-----


1. Always use jslint.

2. Read good JavaScript (as others have said). The jquery source is a good place to start. Underscore.js is good, too. Unfortunately there isn't consensus about what is and what isn't good JavaScript. Some people seem to be suggesting Prototype as an example of good js, which I would disagree with.

-----


> 1. Always use jslint.

Or jshint!

-----


Do a side project that will require you to write a lot of javascript. Try not to use libraries like bootstrap that do a lot for you.

If you write a lot of js, you'll probably write messy js, but you'll understand how it can so easily get out of hand.

Then read a lot of code and the other resources people have linked to here. Having done a lot from scratch will motivate the solution a lot more.

You will have actually run into the problems they are telling you to solve and understand why it's good js rather than just taking their word for it.

-----


Learn Lisp. Realize that JavaScript is a lot like Lisp, but with better libraries and C-like syntax. Then write really good JavaScript.

-----


> Learn Lisp. Realize that JavaScript is a lot like Lisp,

This would have been true a long time back when Lisp was the language with first class functions, closures etc., but today every other languages have those and JS is a lot closer to them Lisp.

Even if this was true, why not learn JS and skip the Lisp part?

> but with better libraries and C-like syntax.

May be with better 3rd party libraries. Out of the box, JS standard library sucks.

-----


Sexps aside, no continuations, no TCO, and no macros mean that JS is actually pretty far from Lisp.

-----


It's Scheme that has continuations and TCO (guaranteed by the spec) -- Common Lisp has neither, I believe.

-----


I think you're right. What I was trying to point out is that learning "Lisp" (which one?) is not a good way to get better at Javascript. Lua or Io - maybe, but even then the suggestions of other people in the thread for actual JS resources are so much better.

-----


Shameless plug I wrote an article called "OO JS in 15 minutes Or Less" that did really well hacker news in addition to others. Feel free to check it out :)

http://beardedocto.tumblr.com/post/21920818233/oo-js-in-15mi...

-----


This book by Mikito Takada (mixu) has been the single most important read in my JavaScript development: http://singlepageappbook.com/

Very well written, well explained, and it points to many more best practices.

-----


Three simple steps.

1. Read Douglas Crockford's Javascript: The Good Parts (Alternatively you can watch his lectures on Yahoo Theater)

2. Read Nicholas Zakas' Maintainable Javascript and Scalable Javascript.

Trust be both these books will make a great difference to the way you write your javascript code.

The next step should be to contribute to some open source JS frameworks. I will suggest jQuery or YUI. You need not always write code, you can begin with improvements to the documentation and later move on to submitting actual code.

-----


I didn't grok Javascript until I started using node.js. I soon realized jQuery is not Javascript, which is what many people think Javascript is just like many think Rails is Ruby.

Just do it! Google things as you learn. Try writing a RESTful todo app with Backbone on the client and node on the backend. You'll soon learn async patterns, closures, constructor functions and most importantly understand how `this` works. Those along with `apply` I think are the essentials to being an effective Javascript programmer.

-----


If you're okay with paying, John Resig (creator of jQuery) is in the process of writing a great book - "Secrets of the JavaScript Ninja" - which is available as an early access edition here : http://www.manning.com/resig/

I assure you, its worth the money.

Note: I am in no way associated with the publishers or author apart from being a beneficiary of this awesome repository of knowledge. This is not even an affiliate link.

-----


My employer will be paying, so I am OK with that ;)

-----


You may also want to take a look at SlickGrid https://github.com/mleibman/SlickGrid

It is a datagrid developed using pure javascript and jquery. The codebase is one of the best that I have seen in my life so far. Proper use of separation of concerns, responsibilities. Very neat use of oops, methods.

There are lot of examples which will teach you great stuff.

-----


Id say just like with any language, you need to ensure that your objects do one(or a few) thing(s) well. Read this article about dependency injection with JS http://merrickchristensen.com/articles/javascript-dependency... if you're able to model your code in a manor that fits that pattern, you'll be off to a great start

-----


Apart from all the wonderful resources listed here, one thing that really thought me a lot was writing stuff without using a library like jQuery. Try writing browser-compatible event handlers (you'll find quirksmode.org an immensely helpful resource), an AJAX request, a simple pubsub/observer pattern, etcetera. This will learn you a lot about the language, and it'll be a lot of fun too!

-----


This is one of the best resources I've found that highlights all the silly things about javascript. It doesn't treat you like a beginner, it's just information about gotchas

http://bonsaiden.github.com/JavaScript-Garden/

-----


Keep an eye on the up and coming http://effectivejs.com/

-----


I'm currently going through Javascript Enlightenment by Cody Lindley. I think in the end you have to re-read lots of the same topics cause one author's way of phrasing certain things will 'click', and then another author's will add on to the 'click'.

-----


For OOP JavaScript, I suggest you check out this link: http://killdream.github.com/blog/2011/10/understanding-javas...

-----


http://dmitrysoshnikov.com/ top right hoover over "Menu"

-----


I can also recommend Javascript Patterns and Javascript Web Applications by O'Reilly. They're both solid books.

-----


The Definitive Guide to Javascript by David Flanagan is incredibly comprehensive (and only $5 on Android)

-----


A lot of people have listed a lot of different things. If I were in your shoes, I'd be pretty overwhelmed.

There is only 1 book you should start with, "Javascript, the Good Parts". It only talks about the language, not DOM apis. If I were teaching any student javascript, I would always start with that book.

As for the rest of it, learn the language. Avoid Coffeescript, Typescript, or any other DSL that purports to "compile" to javascript. You'll only be doing yourself a disservice. Just worry about learning the language first. This is vital to understand what's going on.

-----


Consider using a framework that forces you to write orthogonal code...backbone, ember, spine, etc

-----


Well, first things first, you must be aware that JavaScript is a bad language, broken in many ways and mostly executed in a random fashion (i.e. almost no platform follows 100% ECMA, and even some ECMA directives are retarded, like ECMA4 didn't force chrome to return object properties in creation order by default, whereas ECMA5 fixes that to the default behavior we've always seen and expected).

In that sense, writing good JavaScript is like writing good PHP or good C++, it's a lot about avoiding the broken features (for both those languages, there are a lot of features one shouldn't use, it's even more true with js).

That means you should only learn from people who recognize how broken js is, and thus of course js: the good parts sounds like the right direction, whereas I think Resig is a religious zealot and shouldn't be listened to (the guy actually thinks broken js as a first language is a good idea).

Lastly, js is broken in many ways, don't use it when you don't have to, that means avoid node.js and use a good server side language instead.

tl;dr js sucks, don't listen to people who don't ack that, learn to avoid the sucky parts instead.

And more downvotes from the zealots... HN is so predictable these days.

-----


Dear Troll, I find you use of the word "zealot" to be amusing, ironic and predictable. In addition, during that entire rant you never once mentioned what you thought was a good language.

Now, to add to the real discussion. Aside from all the wonderful suggestions you received so for: once you have read all that you can and broken/learned first hand all you can, and if you are of the pattern persuasion I would look in to the functional language patterns. The Classical patterns, as found in most examples and resources these days, map poorly to JS. At least that is my opinion.

-----


Amusingly, his post is actually more or less what Crockford says in the opening page or so of JavaScript the Good Parts.

-----


good for you.

I haven't seen a perfect programming language yet, but the compromises offered by FORTRAN, C, Ada and lisp are really hard to beat, as the first three offer very competitive speed whereas the last one trades off about 50% speed for a lot of built-in metaprogramming.

It's really all about compromises, and JS fits no bill except "easy to learn for noobs", which imho is a non-issue for anyone considering long-term use.

(in case you didn't know, fortran has awesome arrays and awesome compilers, C has inline ASM and awesome compilers, Ada has increased execution security and lisp is lisp)

-----


JavaScript is harder to learn for noobs, it's just easier to get "hello world" working than other languages. I don't think anyone with a good grasp of JS would ever recommend it to someone as a first language.

-----


Well, this is an Ask HN thread and your answer boils down to "learn to avoid the sucky parts", which is good advice, but instead of further guidance on how to achieve this, the remainder of this post contains nothing but useless rants. (Useless for the OP, that is.)

Look at the top rated posts in the thread, all of them contain a ton of specific advice on avoiding the sucky parts.

-----


Actually my advice boils down to :

Avoid the sucky parts by listening to people who recognize the suck.

And that's exactly why it is an addition to the existing answers, most of which do not focus on that core point, and some of which even advise to read documentation written by people who don't recognize the failures of JavaScript.

-----


Javascript is simple , but it comes with 0 battery included. The most difficult thing is not javascript itself but it is to work with the DOM which is a strongly typed and inconsistant API written in C++ most of the time ( yes it is , you cant say it is not and still get those Node errors ...) The only book you need to read about javascript is "The Good Parts" by Douglas Crockford and read the available ECMASCRIPT specs, which is mandatory if you are serious about Javascript. The rest is mostly garbage.

-----




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: