3 Tips To Write Better Code As A Beginner Frontend Developer
--
As a beginner, you don’t think about coding style. Implement these three principles to improve your code base immediately.
Over the course of the last months, I had the opportunity to mentor a group of talented new web developers who participated in TechLabs’ digital shaper program.
It was really fun to see the groups’ learning progress from zero to deployed application. While I was reviewing their first bits of code, it reminded me of my first years as a developer.
Especially if you are self-taught and don’t have any formal education, you just rock n roll. You don’t have any feeling for good or bad code practices. You are happy about anything that works.
This got me thinking: “Which coding principles do I wish I had known earlier?”. Well, here they are!
You can implement these simple tips in your coding practice right away. But although simple, they changed a lot in how I write code.
Note: The principles are applicable to all areas of programming, even though the title says ‘frontend developers’ specifically.
1. “Return Early” Instead Of Nested Conditions
In web development, you have a lot of situations in which you have to check if certain conditions are met.
Let’s take the example of an API route that validates a request and returns an user object:
export const handler = async (req, res) => {
if (req.method === "POST" || req.method === "OPTIONS") {
const email = validateEmail(req.body.email);
if (email) {
const user = getUserByEmail(email);
if (user) {
return res.status(200).json({ user });
} else {
return res.status(404).json({ message: 'No user found' });
}
} else {
return res.status(422).json({ message: 'Missing email' });
}
} else {
return res.status(405).json({ message: 'Unsupported message' });
}
}
Although we don’t have that much of logic incapsulated in this function, it already looks quite a bit cluttered. Specifically, there are two issues with this code:
- It is hard to follow the flow of code. Instead of reading top-to-bottom, we need to read left-to-right…