Skip to content

mk4111/javascript-best-practice

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 

Repository files navigation

javascript-best-practice

This repo has been forked from dwyl, and has been modified to reflect my personal opinions and learning experience. I hope to upate this repo with rules and methods that I think contribute to 'better' code.

Sources:

dwyl's javascript-best-practice dwyl's best-practices

Keywords:

#consistency #maintainability #performant iterability robustness

Summary of what you're about to read:

  • Indentation = 4 spaces.

  • Max line length = 80 chars. Continue a line by indenting two levels.

  • Use double quotes. Always. (Why?)

  • Keep it modular. Split out functions into files, never let your app get too big; break up your app into smaller chunks. Design your code to work in isolation.

  • Reducing the amount of code in your product should be your goal - Jack Diederich

  • Testing: Always TDD. Test what the client will see/should expect.

  • Architecture: it should resemble your domain, not the framework you are using.

  • Dependencies: keep them lean.

  • Simple is best.

Questions to ask:

  • Are you rewriting or refactoring?
  • Could this be premature optimisation?
  • Is your code really working? Have you tested from all angles?

Main Rules

  1. Use the “Good Parts” (and avoid the “Bad parts”)
  2. Clear, Concise and Commented Code
  3. Meaningful Variable and Parameter Names --> the challenge: make it as short as possible all the while making it meaningful to new devs coming onto the project.
  4. Avoid Global Variables
  5. Use JSLint to ensure your code is consistent; decide on rules at the beginning of a project, and stick to them.
  6. Always Unit Test your Code (even for simple/quick fixes and one-liners) - preferably TDD it!
  7. Learn (“Real”/”Raw”) JavaScript (fundamentals) before using Libraries like JQuery/Backbone
  8. Avoid Libraries/Modules/Frameworks until you understand them. especially when they are un-tested/documented if(tests===false) alert(“Don’t use it!”)
  9. Never Commit/Ship Broken/Buggy Code even when “PMs” Pressure You!
  10. Its only “Done” when its “Documented”.

Extra Mile

  1. Learn CoffeeScript it will Set you Free!
  2. Learn & Use Patterns
  3. (Don’t be afraid to) Critique someone else’s code if they ignore any coding best practices (by pointing to the specific “guideline” that is not being followed)
  4. Compile your code with Source Maps (to aid debugging)

Read:

Maintainable JavaScript (Nicholas C. Zakas 2010) - contains practical JavaScript best practices.

Indentation

Indentation should be four spaces not tabs.

// Good
if (true) {
    makePandaHappy();
}

Line Length

Max line length = 80 characters. Lines which go over 80 char should be wrapped after an operator (e.g. comma). The continuation line should be *indented two levels (8 chars).

// Good
registerNewUser(firstName, lastName, emailAddress, password,
        preferredLanguage);

// Bad: Continuation line only indented four spaces
registerNewUser(firstName, lastName, emailAddress, password,
    preferredLanguage);

registerNewUser(firstName, lastName, emailAddress, password
        , preferredLanguage);

Note: there are plenty of advocates for "Leading Comma" or "Trailing Comma" see: http://www.sencha.com/forum/showthread.php?6796-Leading-comma-or-Trailing-comma-that-is-the-question.

Primitive Literals

Strings

Always use double quotes and span a single line.

// Good
var message = "Welcome to JayessVille!";

// Bad: Single Quotes
var message = 'single quotes confuse. avoid';

Recommended Reading

Best Teachers

Completely New to JavaScript? Welcome! Start with this book:

  • Dom Scripting: Web Design with JavaScript and the Document Object Model - www.amazon.com/dp/B004VH7LQE BUY IT! Invest in knowing how to build the future! (if you cannot afford the $18 for a secondhand “like new” copy, get in touch, I will lend it to you!)

If you are familiar with JavaScript and not yet read “The Good Parts” start!

Once you have mastered the Good Parts, hone your craft:

Now that you know the language its time for Test Driven Development!

And/or Behaviour-Driven Development (BDD):

Time to Optimize your JavaScript? (Or looking for some simple wins?)

Maintainable JavaScript (Nicholas C. Zakas 2010) - contains practical JavaScript best practices.

CoffeeScript

I am a huge fan of CoffeeScript's elegance and simplicity. But its not as popular as I would have liked. :-(

Easy to Write Hard to Read

I actually find CoffeeScript incredibly easy to read (practice?) but I agree with @pgte its harder to get contributions from others for open source projects if they are written in CoffeeScript, simply because not that many people know the language! :-(

I still recommend you learn coffeescript, its so much more fun to write and (with practice) read than JavaScript! And for small teams where everyone learns it, CoffeeScript wipes the floor with JavaScript!

Further discussion:

Book

The Little Book on CoffeeScript: http://www.amazon.com/dp/1449321054/ Available FREE at: http://arcturo.github.io/library/coffeescript/index.html

Learn By Doing

Learn CoffeeScript by Testing with the “Koans”: https://github.com/sleepyfox/coffeescript-koans

Small Stack of Best Books

While I'm a strong advocate of learning by doing, sometimes it pays to learn from the knowledge/mistakes of more experienced people by reading the books they have written...

I keep a small stack of the best titles on my desk to recommend to my "junior" developers:

Stack of JavaScript Books

If you live in London and can't afford to buy books, message me on LinkedIn, I'm happy to give you any of my books in exchange for insights. :-)

Test Driven Development - Writing Reliable Code

If you are not doing Test Driven Development (TDD), you are officially an ammateur; go do your homework! But seriously, testing is easy and will give you confidence in the code you have written.

Writing comprehensive tests allows you to refactor your code as you learn how to do things more efficiently (natural progression - you’re meant to keep learning; honing your craft!) and can build on your existing codebase without fear of breaking existing (decoupled) modules.

There are a wide range of options for testing JavaScript: See: http://stackoverflow.com/questions/300855/looking-for-a-better-javascript-unit-test-tool

I recommend reading http://www.amazon.com/dp/0321683919/ and http://www.amazon.com/dp/1449323391/ to get a good understanding of the available options.

I have used:

And of these I favor Jasmine for its Simplicity. (but always keep open mind if someone has experience of others)

Jasmine

Notes

Sources

History

This originally started out in a Google Doc: https://docs.google.com/document/d/1t9msoVNY5KlRnHeIAgUgqDyaXh2Q35v5zHtdpZ2vy-U I created it to share/suggest best practices with my team of developers. The idea was that all developers in the company could edit the doc and a generally agreed code for writing code could be established.

The reality was that I was the only one who even looked at the Google Doc! Nobody made any comments or contributions. :-( Too "Busy" coding to stop and think: "Is my code consistent...?" or "Is this maintainable by someone else?" ... This is not the time or place to voice my frustration at trying to get people in an established organisation (with more bad habits than you can imagine) to adopt industry best practices for JavaScript code. Each to their own.

Its time to put this up on GitHub for a wider audience to access. ;-)

About

A collection of JavaScript Best Practices

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published