Clean Code in JavaScript_ A Comprehensive Guide ? - DEV Community
Clean Code in JavaScript_ A Comprehensive Guide ? - DEV Community
Alaa Samy
Posted on 22 feb • Edited on 24 feb
84 4 6 5 7
Writing clean code is an essential skill for any developer. Clean code isn't just about
making your code work—it's about making it work elegantly, efficiently, and in a way
that other developers (including your future self) can easily understand and maintain.
In this comprehensive guide, we'll explore the principles and best practices of writing
clean JavaScript code.
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 1/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
Your variable names should clearly indicate their purpose and context.
// Bad
const d = new Date();
let u = getUser();
const arr = ['Apple', 'Banana', 'Orange'];
// Good
const currentDate = new Date();
let currentUser = getUser();
const fruitList = ['Apple', 'Banana', 'Orange'];
// Bad
var API_ENDPOINT = 'https://api.example.com';
var MAX_ITEMS = 100;
// Good
const API_ENDPOINT = 'https://api.example.com';
const MAX_ITEMS = 100;
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 2/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
// Bad
setTimeout(doSomething, 86400000);
// Good
const MILLISECONDS_IN_A_DAY = 86400000;
setTimeout(doSomething, MILLISECONDS_IN_A_DAY);
// Bad
class User {
constructor(name) {
this.name = name;
}
}
// Good
class User {
#name; // Private field
constructor(name) {
this.#
#name = name;
}
getName() {
return this.#
#name;
}
setName(name) {
this.#
#name = name;
}
}
class BankAccount {
#balance = 0; // Private field
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 3/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
deposit(amount) {
if (this.#
#validateAmount(amount)) {
this.#
#balance += amount;
}
}
// Bad
function processUserData(user) {
validateUser(user);
updateUserInDatabase(user);
sendWelcomeEmail(user);
updateUIWithUserData(user);
}
// Good
function processUserData(user) {
if (validateUser(user)) {
saveUserData(user);
}
}
function saveUserData(user) {
updateUserInDatabase(user)
.then(sendWelcomeEmail)
.then(updateUIWithUserData);
}
// Bad
function createUser(firstName, lastName, email, age, location) {
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 4/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
// ...
}
// Good
function createUser(userConfig) {
const { firstName, lastName, email, age, location } = userConfig;
// ...
}
// Bad
function proc(data) { /* ... */ }
// Good
function processUserPayment(paymentData) { /* ... */ }
Your code should be clear enough that it doesn't need extensive comments.
// Bad
// Check if user is adult
if (user.age >= 18) { /* ... */ }
// Good
const isAdult = user.age >= 18;
if (isAdult) { /* ... */ }
// Bad
// Iterate through users
users.forEach(user => { /* ... */ });
// Good
// Filter inactive users before sending notifications to avoid
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 5/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
// overwhelming users who haven't logged in for 30+ days
const activeUsers = users.filter(user => user.lastLogin > thirtyDaysAgo);
// Example test
describe('User Authentication', () => {
it('should successfully login with valid credentials', () => {
const user = new User('test@example.com', 'password123');
expect(user.login()).toBeTruthy();
});
});
// Bad
const streetName = user && user.address && user.address.street;
// Good
const streetName = user?.address?.street;
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 6/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
- Utilize Destructuring
// Bad
const firstName = user.firstName;
const lastName = user.lastName;
// Good
const { firstName, lastName } = user;
// Bad
function greet(name) {
name = name || 'Guest';
return `Hello, ${name}!`;
}
// Good
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
Conclusion
Writing clean code is an ongoing journey of improvement. It's not just about
following rules—it's about developing a mindset that values clarity, simplicity, and
maintainability. Remember:
By following these principles and continuously refining your approach, you'll write
code that's not just functional, but truly professional and maintainable.
References
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 7/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
https://www.freecodecamp.org/news/the-clean-code-handbook/?ref=dailydev
https://www.youtube.com/watch?
v=b9c5GmmS7ks&list=PLWKjhJtqVAbkK24EaPurzMq0-kw5U9pJh&index=1
Timescale PROMOTED
Read More
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 8/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
// Don't!
class User {
#name;
constructor(name) {
this.#
#name = name;
}
getName() {
return this.#
#name;
}
setName(name) {
this.#
#name = name;
}
}
const user = new User(name);
// Just do
const user = { name };
See how much complexity vanishes just because you handle data as data and
not as class?
💯
Also, if you really need to set a getter and a setter, you could also use the
newer and leaner syntax get name() and set name(name) .
Unless you need to pass arguments too (which is generally bad IMO, as
long as the method name suggests a simple data read).
Wow, what an awesome deep dive into clean JavaScript code! 🚀 This guide
is a goldmine for anyone looking to level up their coding game—whether
you're a newbie or a seasoned dev. I love how you broke it down into
actionable tips like meaningful variable names (goodbye, cryptic d and arr!)
and keeping functions small and focused. That “do one thing” rule is a game-
changer—I’m guilty of writing those monster functions that try to do
everything at once. 😅
about writing comments for “why” instead of “what”? Spot on. It’s so
tempting to over-comment the obvious stuff instead of explaining the real
intent.
Quick question for the community: How do you all handle naming
conventions in big projects? I’ve been leaning toward camelCase for
consistency, but I’d love to hear your strategies! Also, any favorite tools or
linters you swear by to enforce clean code? (ESLint fans, where you at?)
Thanks again for your kind words and for joining the discussion! 🚀
JakeHadley • 23 feb
I really love the ai generated circle of interactions y'all got going on. It's
almost like it's real life. Great ai article as well. Maybe I should do one on
Rust clean code when I know nothing about Rust.
created.
I'd genuinely encourage you to write and share your knowledge! and I'd
be happy to discuss any specific points about clean code practices in
JavaScript if you have questions or insights to share.
Jake, feel free to keep away from AI and the great tools it offers.... and
get left behind. In that same spirit you MUST turn off your IDE and stick
to notepad, and throw away canva and photoshop and pull out your
trusty paintbrush and canvas.... if we are going to be critical of one tool
available, might as well be critical of all tools.
// Good
function processUserData(user) {
if (validateUser(user)) {
saveUserData(user);
}
}
function saveUserData(user) {
updateUserInDatabase(user)
.then(sendWelcomeEmail)
.then(updateUIWithUserData);
}
All of these functions are inpure because use some outer dependency like
saveUserData(user)
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 11/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
If we would like to make our function with outer dependency are testable
then better to use dependency injection:
/**
* @type {(
* updateUserInDatabase: (u:User) => void,
* sendWelcomeEmail: (u:User) => void,
* updateUIWithUserData: (u:User) => void,
* ) => ( u:User ) => Promise<void> }
*/
const saveUserDataFactory = (
updateUserInDatabase,
sendWelcomeEmail,
updateUIWithUserData,
) => async (user) =>
updateUserInDatabase(user)
.then(sendWelcomeEmail)
.then(updateUIWithUserData)
;
Yangren • 23 feb
Good article, thank you :) I didn't quite understand your example on naming
conventions though. Can you explain why getUserInfo , getClientData and
getCustomerRecord have inconsistent naming and are bad?
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 12/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
confusing to someone who reads the code and might not recognize what
these functions are related to.
Also, these naming variations make it hard for developers to remember
and search in the code, and figure out which function to call.
I hope this clarifies things for you, Feel free to ask any further questions
That's good, but don't explain in the comments: explain in the article.
I think is because all of them have different names for the same
functionality, get the user data (sorry for any mistakes, English isn't my
native language)
Author, answer honestly: did you make use of AI to write this article?
Many points are fine (some are quite naive), but they're all under-explained,
and the examples often do no justice to the principles. Hand-crafted
examples don't usually suffer from this problem; AI generated ones usually
do. Also, AI often uses older JS syntax (e.g. getName() instead of get name() ,
instead of ?? - which is a little ironic because it's in the section "Modern
||
JavaScript Features") (also those greet functions are not equivalent: try
passing an empty string, and see how the "bad" one probably does what you
actually want, while the "good" one fails).
And you didn't mention that if you want to write unit tests like those, you
need a library like Mocha/Jest/Vitest/etc. And the fact that those are unit
tests, while you probably also need integration, end-to-end, performance
and accessibility tests too. And more.
If you want to make clear why a principle produce clean code, take
inspiration from ESLint's rule explanations (e.g. how they explain
destructuring). They show a lot of general use cases, options and nuances for
every rule.
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 13/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
You're right about the depth of explanation, but this post was intended as a
high-level overview to introduce these concepts, particularly for developers
newer to clean code practices, and each point of these principles need a
follow-up article to cover it in more detail.
And I want to clarify that the principles shared come from my practical
work with JavaScript and studying clean code principles, I did use AI tools
to help in organizing the content (not writing the code), similar to how
writers might use tools like Grammarly or editors to improve clarity.
Regarding the greet function examples, you're right that the 'bad' example
do better that the 'good' one, but these examples were intentionally
simplified to demonstrate the concept of using default parameters over
logical OR for defaults. In a real-world application we would need more
validation for each function.
Riccardo • 23 feb
Good information
sentinelae • 24 feb
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 14/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
Some "cleaner" ways of doing things are less performant. Where do we draw
the line?
Pieces.app PROMOTED
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 15/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
Our centralized storage agent works on-device, unifying various developer tools
to proactively capture and enrich useful materials, streamline collaboration, and
solve complex problems through a contextual understanding of your unique
workflow.
Learn more
Alaa Samy
LOCATION
Alexandria, Egypt
JOINED
13 mar 2024
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 16/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
[Boost]
#webdev #programming #javascript #cleancode
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 17/18
24/02/25, 20:37 Clean Code in JavaScript: A Comprehensive Guide 🚀 - DEV Community
https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j 18/18