JavaScript – Tips to Help you Write Cleaner Code

It doesn’t matter whether you are working on a home based project, a large corporate project for the company you work for or even if you are a freelance developer. The importance of clean code goes without saying.

Your ability to suitably maintain your code will rely on how much your earlier inserted code to hack and slash your way to something that works (especially for those head scratcher functions you never thought possible). This even goes for improperly named or placed variables and methods.

Take for example JavaScript. JavaScript isn’t a pure functional language, it’s Java’s baby brother so many have said in the past really. It’s creator also made a similar comment:

JS had to “look like Java” only less so, be Java’s dumb kid brother or boy-hostage sidekick. Plus, I had to be done in ten days or something worse than JS would have happened – Brendan Eich

Tips to help you write cleaner code

If your reading this in retrospect, then the below (none-exhaustive) bulleted checklist will help you clean up your code:

  • Fix bad spacing and indents
  • Fix any inconsistent quotes
  • Fix unstable code
  • Fix typo’s and spelling mistakes
  • Fix badly names variables

There are many more things you would need to take a look at such as deleting unneccessary whitespace, line breaks and my favourite, redundant comments. Run a Google search on code cleanliness and you’ll get a host of other things to think about before declaring your life’s work of JavaScript ready for the big bad world.

Now the negative stuff is out of the way. Here are some tips on organising your code once you’ve cleaned it up a bit:

Modulize/Compartmentalize your code

Simple, don’t dump all your code into one big JS file. Think about sectioning it off into separate files based on functionality type.

Create a plan for your code

In User Experience, planning is a must. This is no different when coding in JavaScript, jQuery or any or JS library. Too often many will simply plough ahead and then three quarters of the way through realise that they have to go back and re-write some code.

Version Control your code

This is more applicable when working with more than one person or a larger in a team. If something breaks along the way of the project, it’s much easier to backtrace and fix it!

Validate your code

There are some great tools out there like JSLint fo example that can help ensure that your code works properly. One small mistake may go unnoticed in some browsers (not so in Internet Explorer), but several will end up breaking your code and you’ll have no idea how it happened until it’s too late.

Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.