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! 😕
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
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.
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.
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:
30+ common code smells & how to fix them
15+ design pattern practices & how to apply them
20+ common JS bugs & how to prevent them