Writing Vanilla JS that you can support

– JS can suck when written badly

Everybody have heard at least on person to say that JavaScript is bad because it’s messy. And everybody have seen a poorly written JS. The big pros of JS makes some people think that they lead to hige cons.

Everybody loves to use JS to get a small thing done but when it comes to doing something with more than N lines of code things can get messy. Not that in other language this is not the case but with JS most of the time they do get messy. And that’s not because the language is that bad. It’s because the language is that easy.

Anybody starting to do anything with web meets his new friend JS and everybody deals with it the way he can (in most cases this means hacking into it). The thing with JS is that actually hacking into it without exactly knowing what are you doing is perfectly fine (for getting small things done). And since huge amount of people have hacked their way through JS you get huge amount of hacky solutions and sometimes.. really often crappy code.

Well… You actually can write good code with JS. And you don’t have to learn a framework (like Angular or etc.) for that. The key is not forgetting that writing JS is still programming. So you can follow some of the nice programming principles:

1. Thinking before coding

Well JS is this type of language that is not compiled, bla-bla-bla, so you can code quickly and see the things you’ve written isntantly (no long compiles-builds-links-etc). So that’s where most of the people just start writing. I think that’s the first and main step to writing good code – thinking up front and drawing/writing on papaer what you want to achieve.

2. Modules

In the thinking part you have to separate the things you do into smaller chunks of functionalities. Make these chunks modules and make them logically independent – you are making an app with map, menu and data sync with a server – you might want to have a module for the map related code (map.js), one for menu related code (menu.js) and one for data sync related code (data-sync.js).

3. Logical app.js

An app.js file should be very easy to read. It should do two things:
– Call the init functions of the modules (or just trigger an init event)
– Bootstrap the app (initiate the action related to starting the app – get the data from the server after )

– Thinking before writing always helps

– Use the tehniques: types for data structures, modules for separate functionalities, extending modules for adding functionality to a module, events for comunication through the app, app.js with initing and bootstraping fucntion only.


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.