Getting Started with Code Formatters
Code formatting is for humans
Code doesn’t need to be formatted in order for the computer to run it. There are exceptions, such as Python, that include indentations as part of the syntax. Even though computers don’t need formatting, humans do.
Styling code is essential and should never be an afterthought. Compare how easy it is to read these lines:
// Ahh, so easy to read
function isEven(n) {
if (n % 2 === 0) {
return true;
}
return false;
}
// Oh no, this is not good
function isEven(n) {
if (n % 2 === 0) {
return true;
}
return false;
}
// Omg, one-liner hell
function isEven(n) {
if (n % 2 === 0) {
return true;
}
return false;
}
All developers must vow to always format code. However, I understand that manually formatting code can be cumbersome. Missing indentations here or there. Deleting a line and having to shift code around.
The solution? Code formatter!
Popular code editors such as Sublime Text, Atom, and Visual Studio Code (VS Code) have code formatting plugins available.
Popular code formatters
These two are my favorite for projects. There are plenty of other wonderful formatters for any language that you need.
- Beautify - JavaScript · JSON · CSS · Sass · HTML
- Prettier - JavaScript · TypeScript · Flow · JSX · JSON · CSS · SCSS · Less · HTML · Vue · Angular · GraphQL · Markdown · YAML
Play around with different formatters to see what you like. If you’re not sure which one to start with, try Prettier. It’s an opinionated formatter that will format code the same way for everyone.
Bonus tip for better formatting
I have a tip to further improve formatting magic. In your code editor, turn on Format on Save
after installing your chosen formatter.
In VS Code, go to Code > Preferences > Settings > Text Editor > Formatting > Format on Save.
Gone are the days of pressing tab (or space) buttons.
Beautiful code is just one save button away.