How to write clean code in Javascript: 5 keys with examples

Hello developers! πŸ‘‹ Today, let’s talk about something super important: clean code. No matter what programming language you use, clean code makes your life easier. In this post, I’ll explain what it is, why it matters, and some simple rules to follow. Let’s go! πŸš€

By the way, this is a written version of my first video on Youtube 😊

What is Clean Code?

Clean code is easy to read and understand. When you or someone else checks the code, it should be clear what each part does. No guessing, no magic numbers, no confusion. Just clear logic! βœ…

Why Should You Care?

  • Maintenance πŸ› οΈ – You, your team, or another developer will need to update the code later. Clean code makes it faster and easier.

  • Productivity πŸ“ˆ – When your code is clear, debugging and onboarding new developers is much easier.

  • Quality πŸ† – Clean code usually means fewer bugs and lower development costs.

Common excuses

Sometime we can hear:

❌ β€œWe need to move fast!” β†’ But messy code slows you down in the long run.

❌ β€œWe don’t have time!” β†’ We are always in a hurry, but quality is more important than speed.

❌ β€œPerfection is impossible!” β†’ True, but we can always improve! πŸ’ͺ

How to Write Clean Code

Here are some simple rules to follow:

  • πŸ“ Use Descriptive Naming – Choose names that show the real purpose of the variable or function. Avoid abbreviations or vague names.

  • πŸ”„ Be Consistent – Use the same terms across different parts of the code. If you call something getUserData in one place, don’t call it fetchUserInfo elsewhere.

  • πŸ“ Short Functions & Files – Avoid long functions. Break them into smaller, meaningful parts to make the code easier to read.

  • πŸ’¬ Replace Comments with Self-Explanatory Code – Instead of writing comments to explain what a function does, improve the function name and structure.

  • πŸ‘€ Readability Over Performance – Don’t write β€œsmart” but unreadable code. Clear code is better than a few milliseconds of performance gain.

Examples ✍️

Naming πŸ”‘

if (age == 18 && car && car.ok()) {
 car.drive([40.4670213, -3.8013119]);
}

You may think:

  • Why 18? Magic number πŸ‘Ž
  • What does ok() mean?
  • Which are these coordinates?

Better?

const isAdult = age === ADULT_AGE;
const hasCar = car && car.isOk();
const canDrive = isAdult && hasCar;
const {lat, lng} = office;
const destionation = [lat, lng];
if (canDrive) {
  car.driveTo(destination);
}

Consistency πŸ”‘

function getEvents() { ... }
function fetchEvents() { ... }

You may think:

  • What are the differences?
  • Are these functions the same?

Better?

function getEvents(filters = {}) { ... }

Avoid long code πŸ”‘

function downloadFile(params) {
 Logger.debug(`downloadFile() starting download file: ${url}`);
 if (!url || !url.startsWith(URL_PREFIX) {
   throw new Error(`downloadFile() Invalid url ${url}`);
 } else {
   return http.get(url, params, (response) => { 
      ... 
   }
 }
}

Better?

function downloadFile(params) {
 await validateFile(params);
 try {
   return await fetchFile(params);
 } catch (error) {
   return await retryFile(params, error);
 }
}

Self-explanatory code πŸ”‘

if (null === value[field]
  || 0 === value[field]
  || '' === value[field]
  || typeof value[field] === 'undefined') {
    isComplete = true;  
}
return isComplete;

Better?

const isValid = !!value[field];
if (isValid) {
  isComplete = isValid;
}
return isComplete;

Shorter, clean code πŸ”‘

const isIncluded = array.indexOf(item) !== -1;

const hasStreet = user && user.address && user.address.street;

array.map((item) => {
  return item.length;
});


for (const item of array) {
  if (item.property === 'key') {
    foundItem = item;
  }
}

Better?

const isIncluded = array.includes(item);

const hasStreet = user?.address?.street;

array.map(item => item.length);

const foundItem = array.find(item => item.property === 'key');

Takeaways πŸ“Œ

  • Write code for humans, not just machines.
  • Keep it short but readable.
  • Start today! Don't wait for perfection, small improvements make a difference.

Go further ✈️

Want to learn more? Check out these books:

  • Clean Code by Robert C. Martin

  • Refactoring by Martin Fowler

Also, explore open-source projects like Ghost, Next.js, or Babylon.js to see clean code in action.

Let me know your thoughts in the comments! What are your favorite clean code tips? πŸ’¬πŸ˜Š