DEV Community

Cover image for 5 easy wins for cleaner Javascript code 🧹
Mikhail Levkovsky
Mikhail Levkovsky

Posted on

5 easy wins for cleaner Javascript code 🧹

Imagine an empty and clean kitchen sink. It's so shiny you can see your reflection inside of it. If you had a dirty plate, you would probably feel pretty bad just dropping it into the sink, right? You would clean it and put it away.
Now what if your sink is full to the brim, with a bunch of nasty food particles floating around in that nasty water. In that case, you would just throw in your plate because, well, one more plate can't hurt. Unfortunately that is how we treat our code bases as well. Instead of tidying up our code base, we just sometimes throw in more and more code smells.
Well, below are 5 things you can do to start tidying up your code base right now 🚀.

N.B. For some reason, the gists sometimes render in a really weird order. If the code doesn't line up with what I'm writing about, refreshing the page seems to fix it. Sorry about that! 😕

1. Use let and const and forget var

You should no longer be using var, as it can easily introduce variable shadowing and can lead to a lot of confusion. If you need a value that doesn’t change use const. If you need a variable that doesn't change but you will initialize it in the constructor use readonly. If you need a variable who's value does change use let.

pssst I tweet about code stuff all the time. If you have questions about how to level up your dev skills give me a follow @mlevkov

2. Always use string templates

When concatenating strings you should always stick to string templates instead of the concatenation operator. This will make your life much easier as it allows for multiline strings, reduces any errors if your strings have quotes and is generally a lot easier to read. Here is how it would look like when we try to create a database connection string without string templates and with. Think of the kitchen sink. Try to keep your code as tidy as possible.

string templates

3. Object shorthand should be used when possible

Javascript and Typescript goes to great lengths to reduce verbosity. One of my favourite things is that when creating an object with keys, you can use the shorthand annotation to assign your variables to the right keys. Let’s look at an example of us creating a user object in a different way.

4. Merge Your Imports

When importing either your own modules or from installed libraries there are certain conventions to follow. Some of them are less important than others. Personally I don’t care if the imports are in alphabetical order or not. However, if you’re importing multiple things from the same module, you should merge them into one. This will keep your code tidy and keep your imports from being all over the place.

5. Loop through your iterables properly

If you have an iterable, such as an array or a list, and you want to go through the values, you should use the for of instead of the for in. You should use the for in if you want to iterate through the properties (e.g. keys in an array) as opposed to the values. Take for example this method in the Playlist object that will list out all of the names.

There you have it, 5 easy tips that you can use to keep your code base nice and tidy.

If you want to level up your coding skills, I'm putting together a playbook that includes:

  1. 30+ common code smells & how to fix them

  2. 15+ design pattern practices & how to apply them

  3. 20+ common JS bugs & how to prevent them

Get early access to the Javascript playbook.

Top comments (30)

Collapse
 
jamesthomson profile image
James Thomson

Also, use Promises properly. Don't nest Promises, use the chain to call other functions.

e.g.

function getCall () {
  return new Promise((res, rej) => setTimeout(() => res('success'), 2000))
}

function doSomething () {
  console.log('do something else')
}

getCall()
  .then(res => console.log(res))
  .then(doSomething)
  .then(() => console.log('done'))

jsfiddle.net/jamesbrndwgn/4sxty91n/1/

Also, make use of async/await.

Collapse
 
mlevkov profile image
Mikhail Levkovsky

For sure! I have a whole other article coming up on how to clean up promises :)
Thanks for sharing

Collapse
 
_ezell_ profile image
Ezell Frazier • Edited

Is it me or does the advice more-or-less pertain to modern code over 'clean' code?

Don't get me wrong or anything, I like the article and agree with it. However, I'm not going to consider a basic for-loop not 'clean'.

I guess my point is, I'm beginning to prioritize readable code over modern syntax. At my last job, ES6 was completely alien to the team. Everyone was comfortable with writing JavaScript from the mid-late 2000's, with JQuery sprinkled in.

The use-cases never called for more modern syntax.

So when I came along, I still tried my best to build with the 'lowest common denominator' in mind. Should it have to be that way? That's another conversation, but I'm not sure if I'd lump modern syntax and clean code together. The truth is always in the eye of the beholder. If a junior dev can understand what's going on, I'd consider it clean enough.

Collapse
 
mlevkov profile image
Mikhail Levkovsky

I find Javascript and Typescript really try to move towards being as succinct as possible. Sometimes it's a good thing, sometimes not.
I agree that you don't always need the fanciest bells and whistles to get the job done, however it's always nice to learn new things.
Which is why when people say they don't like Typescript because you don't get all the new ES features right away I kind of shrug, because I don't need them.
For loops are fine, I just thought it's important to demonstrate the difference between a 'for of' and a 'for in'. I think using the right type of syntax for the right job and use case is super important.

Collapse
 
mikolaj6r profile image
Mikołaj Romanowski

Actually, your 3rd point is wrong. I dont know how Typescript would behave, but as for JS what You do in second example is assigning variable user to new object. And You loose properties set by User constructor

Collapse
 
mlevkov profile image
Mikhail Levkovsky

You’re absolutely right! I forgot to type it! Will update the gist shortly. Thanks for the catch

Collapse
 
solarliner profile image
🇨🇵️ Nathan Graule

It's not only about Typescript typing; TS is right about changing the type of your variable because you're assigning a completely new value to it. Doesn't matter if it's an User object, or a string or a number, she the assignment, user is an object with the specified values in it. The User prototype is lost.

Collapse
 
akashkava profile image
Akash Kava

VSCode with TSLint with auto correction does more than given examples ...

Collapse
 
mlevkov profile image
Mikhail Levkovsky

Yes of course an entire linter does more than 5 things but a linter is the how and not the why
I think it’s important to demonstrate and explain why we lint certain things and what those rules do.

Collapse
 
akashkava profile image
Akash Kava

For most part, I am not interested in learning why, I am sure people who made TSLint definitely had better understanding, and when you are working many people on team, explaining why would be extremely time consuming and unimportant job. This is the reason, there is only one captain in the team and if captain says use TSLint, follow and do the right job.

Thread Thread
 
mlevkov profile image
Mikhail Levkovsky

We’ll agree to disagree. Personally I never find it a waste of time to explain (or learn) the why. It helps people become better devs and tune the tools they use to their needs.

Collapse
 
moopet profile image
Ben Sinclair

Your first example has the same code snippet for both the "good" and the "bad" version. I think you pasted the wrong one.

Collapse
 
mlevkov profile image
Mikhail Levkovsky

Not exactly :)
In the first example I use var, and in the second I use const
But I guess the example isn’t clear, thanks for the feedback I’ll update it

Collapse
 
moopet profile image
Ben Sinclair • Edited

In the first one you use const, and in the second one you use const!
The only difference is a line of whitespace.

Actually, looking forward, they're both really the snippet for your "for in... for of" comparison later in the post:

example 1

Thread Thread
 
mlevkov profile image
Mikhail Levkovsky • Edited

Wow that is super weird! The gists seem to be rendering out of order :/
Check the screenshot to see what should be there.
I wonder if there's anyway to get support on this from dev.to about this
Can you refresh the page please to see if it's still out of order?

screenshot

Thread Thread
 
moopet profile image
Ben Sinclair

It's working now :)

Thread Thread
 
mlevkov profile image
Mikhail Levkovsky

Thanks for flagging btw
FWIW I added a disclaimer to the top of the article to give people a heads up. So strange

Collapse
 
blackmamba profile image
The Black Mamba🔥

The example snippet for second snippet is actually of the 4th point

Collapse
 
mlevkov profile image
Mikhail Levkovsky

Something really weird is going on with the way the gists are being rendered. They seem to randomly show up out of order :/
Would you mind refreshing the page and seeing if it's still like that?
Thanks

Collapse
 
blackmamba profile image
The Black Mamba🔥

Weird, now it's showing correctly

Thread Thread
 
mlevkov profile image
Mikhail Levkovsky

Ya thanks for flagging it. I put a disclaimer at the top of the post. Super odd

Collapse
 
joepio profile image
Joep Meindertsma

Instead of trying to remember all these, you could use a linter with some sane linting configuration. That way, your editor will tell you whenever you're using a var or have unmerged imports,

Collapse
 
mlevkov profile image
Mikhail Levkovsky

100%. Although I’m not a fan of angular, their linting rules is usually what I follow. This article tries to also demonstrate the why behind the how. I think just slapping on a linter without understanding why isn’t very good

Collapse
 
smz_68 profile image
Ardalan

about first things im not sure but another was good.

Collapse
 
seanmclem profile image
Seanmclem

Are the examples for one and five supposed to be the same thing?

Collapse
 
mlevkov profile image
Mikhail Levkovsky

No, there’s a super weird thing going on where the gists render out of order or get duplicated. No idea why :/
Just refresh the page and it should be good

Collapse
 
arung86 profile image

What about arrow functions? and Async Await, I felt they should have been here.

Collapse
 
mlevkov profile image
Mikhail Levkovsky

Hey Arun

Thanks for taking the time to read it :)
I agree Async/Await and arrow functions are game changers.
I have a few more articles coming up so stay tuned and I'll make sure to cover those topics. There's also these other posts you might find interesting that I have written

  1. dev.to/mlevkov/5-easy-wins-to-refa...
  2. dev.to/mlevkov/5-easy-wins-to-refa...
  3. dev.to/mlevkov/the-holy-trinity-ma...
Collapse
 
dennisk profile image
Dennis Keirsgieter

Your second example seems to be the same snippets as the first? For var/let instead of the string template.

Collapse
 
mlevkov profile image
Mikhail Levkovsky • Edited

A few people have mentioned that the order of gists is all messed up, and sometimes the same gist is duplicated. not really sure what's going on :/
If you refresh the page it usually goes to the normal order