7 Tips to Write Clean JavaScript Code

Learn 7 tips to write clean JavaScript code that is easy to read, maintain, and debug. These tips will help you write better code that is more efficient and reusable.

Your college: “Who’s the author of this code?”

Expectation: “It’s me!” You answer proudly because that code is beautiful like a princess.

Reality: “Nah, it’s not me!” You lie because that code is ugly like a beast.

Now, if you want to make the expectation become the reality, keep reading.

1. Use meaningful Variable Names

Use meaningful names, which you know exactly what it is at first glance.

// Don't
let xyz = validate(‘amyjandrews’);

// Do
let isUsernameValid = validate(‘amyjandrews’);

It makes sense to name a collection type as plural. Thus, don’t forget the s:

// Don't
let number = [3, 5, 2, 1, 6];

// Do
let numbers = [3, 5, 2, 1, 6];

Functions do things. So, a function’s name should be a verb.

// Don't
function usernameValidation(username) {}

// Do
function validateUsername(username) {}

Start with is for boolean type:

let isValidName = validateName(‘amyjandrews’);

Don’t use constants directly because as time pass you will be like, “What the hell is this?” It’d better to name constants before using them:

// Don't
let area = 5 * 5 * 3.14;

// Do
const PI = 3.14;
let radius = 5;
let area = PI * radius * radius;

For callback functions, don’t be lazy to just name parameters as one character like h, j, d (maybe even you, the father of those name, don’t know what they mean). Long story short, if the parameter is a person, pass person; if it’s a book, pass book:

// Don't
let books = [‘Learn JavaScript’, ‘Coding for Beginners’, ‘CSS the Good Parts’];

books.forEach(function(b) {
  // …
});
// Do
let books = [‘Learn JavaScript’, ‘Coding for Beginners’, ‘CSS the Good Parts’];
books.filter(function(book) {
  // …
});

2. Throw Informative Errors

“An error occurs.”

Or just: “Error.”

What error?

Every time I see an error like that in some applications or websites, as a user, I hate it. What do I do wrong? I make that error? So what error? You don’t tell me, how can I know what I’m going to do next?

Your users probably have the same feeling as me. Sometimes they will uninstall your app and never get back.

Writing a clear error message is not hard at all.

If there’s no internet connection, then:

showMessage(‘No internet connection! Please check your connection and try again!’);

If the user forgets to input something, then:

showMessage(‘Please enter your username’);

More importantly, a clear error helps you debug quickly and save you a lot of development time.

if (error) {
  throw new Error(‘validation.js:checkUser: special characters are now allowed’);
}

The above is the error message format you can refer to…

#javascript 

7 Tips to Write Clean JavaScript Code
113.15 GEEK