10 secrets to make your Javascript code perfect

Image credit coolio-claire https://flic.kr/p/9e1JRD
Learnt from the real battle field: at work

After almost 10 years of writing Javascript, I wanted to share my daily tips for writing code. Most of these tips were learnt from co-workers, books or videos. And these technics should not be secret, so I’m going to tell them now!

Before telling you secret tips, I have to confess that I used http://coschedule.com/headline-analyzer to find this title. So yeah, it’s supposed to be attractive but nevertheless I use these “secrets” everyday at work or in my side-projects. And they can be used (almost) without efforts. Ready? Go !

1. Less code = less bug

It might sound obvious, but always keep that in mind. Every part you can remove, don’t hesitate ! Just remove it. Dead code, non used variables, extra parenthesis : every single sign counts.

2. Foster readable code

This is a complement to point 1. Even if you want to keep your code short, always keep in mind that what you write be will be read by humans sooner or later. Maybe someone else, maybe you in few months, and it would be really bad if you took more time to understand it than you spent coding. Remember, code always win; not comments or documentation.

Take care of your variables and functions names, they have to be descriptive enough so you don’t need comments to explain them.

3. Don’t be scared of functions returning function

When I started to code in javascript I didn’t like this way of writing code because I found it hard to follow in the flow of execution. But this pattern is very common and powerful, it’s called closure. It’s really helpful and once you’re used to it, it really helps to structure your code nicely. And it’s the first step in order to dive into functional programming.

4. Extract things

A function is getting too big ? Extract some parts into other functions ! An expression is a bit tricky to understand ? Extract it to a variable and give it a nice name. It really echoes to the point 2, it will make you code more readable. And did you know that our IDE can help? Ctrl + alt + v an expression in Webstorm will extract it in a variable. Ctrl + alt + m will extract it to a function.

5. Bottom up thinking

This is the first step before TDD. You’ll probably always know what you want to achieve. So start by the end, write the result you expect and code the steps backward in order to reach this result. If you make it forward, you’ll probably start to write something, check if it works. Modify it, check, write something else, check and… Maybe it’s not even useful to your goal. Bottom up thinking will help you to keep focus and waste less time.

6. Eliminate the ifs

When you have in mind the single responsibility rule for a function, ifs statements are not your friends. They create branches in the execution flow. And a single little if opens the door to other developpers to add more and more logic into them. In my opinion, if statements should not be allowed without an else. And an if within an if should be forbiden ! Again, it makes complicated code, and often it shows that the function is doing more than one thing. So how to get rid of them ? See the next point.

7. Use lodash _.get instead of null/undefined check

Most of the time, in code reviews I see ifs used to check null or undefined values. But without an else ! So it deals with the “happy” path but leaves the other one open to mysteries (and bugs!).

In order to help you, Lodash (the best javascript ever written) has a very nice function named get. Its first argument is the object you’re working on, the second is the path of children attributes you want to get and the third is the default value, in case of an undefined value.

Two treats for the price of one!

// no more this !
if (account.savings) {
  accounts.savings.join(' ');
// lodash's _.get
var savings = _.get(account, "savings", []);
savings.join(' ');

8. Use ternaries

Some would probably argue that they are less readable, but if you extract things correctly they are a great tool. They also force you to deal with the else case. Plus, they don’t open the door to more code within them.

The less your code looks like a pyramid (of doom), the better.

9. No more for loops, use map reduce and filter

We are getting closer to functional programming here, as these methods are the cornerstones of this style. But without big names or theories, they can avoid very hard-to-read-imperative-style for statements.

These methods are now native in most browsers, so use them ! But if you need back compability use their lodash equivalents.

Now when to use them ?

  • A for statement who deals with all your entries is a map
  • A for + an if is probably a filter
  • A sum or an accumulation is just a reduce !

With these 3 methods combined you can achieve a lot of work in a nice and concise way.

10. Read the sources

When the documentation your tools is not enough then, read their sources ! It will help you to know how to use them and it’ll give a good indication of their quality.

Plus, some libraries have the documentation embed within their sources. So it’s even faster to check them directly. With our IDE we often can go to the source with ctrl + clic on a method’s name.

It’s a good way to kill the magic and grab some inspiration for your own code!

As a conclusion, I would say that these are the principles that worked for me. I wish I learnt them earlier, at school for example… But now you know. And they can be used in almost every context. Some of them are also not bound to javascript, so use them everywhere :)

I’d like to mention the great Uncle Bob and his website https://cleancoders.com/. You should definitively check these videos even if the examples are mainly in Java: the ideas can be applied to Javascript too.