5 easy wins for cleaner Javascript code 🧹
(Source/Credits: https://dev.to/mlevkov/5-easy-wins-for-cleaner-javascript-code-13of)
Imagine an empty and clean kitchen sink. It's so shiny you can see your reflection inside of it. If y...
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.
{% gist https://gist.github.com/mlevkovsky/f04a8eeb3a77f34427d47456b824ad43 %}
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.
{% gist https://gist.github.com/mlevkovsky/aeff9b765d50a767261cf6e659b607f1 %}
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.
{% gist https://gist.github.com/mlevkovsky/d65a8cebe1e4b1561d92f7d1bf34296f %}
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.
{% gist https://gist.github.com/mlevkovsky/5f2c6d98f041cbed786fd4eb6f5949ac %}
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.
{% gist https://gist.github.com/mlevkovsky/ff11a52cea55d581a147608eab323458 %}
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:
-
30+ common code smells & how to fix them
-
15+ design pattern practices & how to apply them
-
20+ common JS bugs & how to prevent them
Get early access to the Javascript playbook.
Comments section
akashkava
•May 1, 2024
VSCode with TSLint
with auto correction does more than given examples ...mlevkov Author
•May 1, 2024
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.
seanmclem
•May 1, 2024
Are the examples for one and five supposed to be the same thing?
mlevkov Author
•May 1, 2024
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
smz_68
•May 1, 2024
about first things im not sure but another was good.
_ezell_
•May 1, 2024
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.
mlevkov Author
•May 1, 2024
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.
arung86
•May 1, 2024
What about arrow functions? and Async Await, I felt they should have been here.
mlevkov Author
•May 1, 2024
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
blackmamba
•May 1, 2024
The example snippet for second snippet is actually of the 4th point
mlevkov Author
•May 1, 2024
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
dennisk
•May 1, 2024
Your second example seems to be the same snippets as the first? For var/let instead of the string template.
mlevkov Author
•May 1, 2024
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
joepio
•May 1, 2024
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,mlevkov Author
•May 1, 2024
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
moopet
•May 1, 2024
Your first example has the same code snippet for both the "good" and the "bad" version. I think you pasted the wrong one.
mlevkov Author
•May 1, 2024
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
mikolaj6r
•May 1, 2024
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
mlevkov Author
•May 1, 2024
You’re absolutely right! I forgot to type it! Will update the gist shortly. Thanks for the catch
jamesthomson
•May 1, 2024
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.
mlevkov Author
•May 1, 2024
For sure! I have a whole other article coming up on how to clean up promises :)
Thanks for sharing