preface

The original address: https://medium.com/javascript-in-plain-english/who-else-wants-to-write-clean-javascript-code-ff4f7896e6bd the author: Amy J. Andrews

Your colleague: “Who wrote this code?”

Expectation: “It’s me!” You’ll answer proudly because the code is as beautiful as a princess.

Reality: “No, not me!” You’re lying because the code is as ugly as a beast.

Now, if you want to make expectations come true, read on.

1 Use meaningful variable names

Use names that make sense so you know what they mean at a glance.

/ / do not recommend
letXyz = validate (' amyjandrews);/ / recommend
letIsUsernameValid = validate (' amyjandrews);Copy the code

It makes sense to name the collection type complex. So don’t forget s:

/ / do not recommend
let number = [3.5.2.1.6];
/ / recommend
let numbers = [3.5.2.1.6];
Copy the code

Describe what the function does. Therefore, the name of a function should be a verb.

/ / do not recommend
function usernameValidation(username) {}
/ / recommend
function validateUsername(username) {}
Copy the code

The naming of Boolean types starts with is.

letIsValidName = validateName (' amyjandrews);Copy the code

Don’t just use constants, because over time you might be like, “What the hell is that?” . It is best to name the constants you need before using them.

/ / do not recommend
let area = 5 * 5 * 3.14;
/ / recommend
const PI = 3.14;
let radius = 5;
let area = PI * radius * radius; Copy the code

For callbacks, don’t be lazy; just name the variable with a letter, such as H, j, or D (even you, the host of these names, may not know what they mean). Long story short, if the variable is a person, pass a person; If it’s a book, pass a book:

/ / do not recommend
letBooks = [' Learn JavaScript ', 'Coding'for Beginners’, ‘CSS the Good Parts’];
books.forEach(function(b) {
  / /...
});
/ / recommend letBooks = [' Learn JavaScript ', 'Coding'for Beginners’, ‘CSS the Good Parts’]; books.filter(function(book) {  / /... }); Copy the code

2 Throw an informative exception

An error occurs.

Or just: Error.

Whenever I see such errors in some app or website, if I were a user, I would hate it. What am I doing wrong? Did I make this mistake? So what was wrong? You didn’t tell me what I should do next?

Your users may feel the same way I do, sometimes they will uninstall your app and never install it again.

Actually, writing a clear error message is not too difficult.

If no network is connected at this time:

ShowMessage (' No Internet connection! Please check your connection andtryagain! ');Copy the code

If the user forgets to enter information:

ShowMessage (' both Please enter your username ");Copy the code

More importantly, a clear bug can help you locate bugs quickly and save you a lot of development time.

if (error) {
  throw new ErrorValidation. js:checkUser: Special characters are now allowed ');}
Copy the code

These are the error message formats you can refer to.

Return as soon as possible

Take a look at the following code:

function login(username, password) {
  if (isValid(username)) {
    // Log in
  } else {
ShowMessage (" Username is not valid "); } } Copy the code

Actually, I don’t need the else part here. We should remove it by returning a message as early as possible:

function login(username, password) {
  if(! isValid(username)) {ShowMessage (" Username is not valid ");    return;
  }
 // Log in } Copy the code

This will make your code much clearer. The edge condition should be placed earlier, and then the longer part, which handles more logic.

Don’t have too much power over one function

Each function should have only one responsibility. Don’t have a powerful function that does too much.

function validateAndLogin() {
  // Do a lot of things here
}
Copy the code

The word and should not be part of the function name. And causes more responsibility to be added to the function, which will do more harm than good in the long run.

The following is best:

function validate() {
  // Only validate
}
function login() {
  // Only login
} Copy the code

5 Avoid side effects

Anything outside the function is not its business. Therefore, the function should not touch any of them.

Such as:

var number = 3;
function changeNumber(add) {
  number = 2 + add;
  return number;
}
changeNumber(); Copy the code

When you call a function that changes number, the value of the number variable is changed to 6. This is a real problem, because sometimes you have no idea that you have changed a global variable. So, you should avoid side effects in your project.

So how do you do that? By using pure functions.

The above example could be changed to this:

function addThree(summand) {
  const CONSTANT = 3;
  let sum = summand + CONSTANT;
  return sum;
}
Copy the code

6 Creating a Module

When you create some function. They seem to be doing something similar. For example, validate user names and passwords. So, you get the sense that they can be grouped into a module. We call this the validation module.

const validateUsername = function (username) {
  // Validate username
};
const validatePassword = function (password) {
  // Validate password
}; Module.exports = {  validateUsername,  validatePassword }; const {  validateUsername,  validatePassword } = require(". / validation ');letIsUsernameValid = validateUsername (' amyjandrews);Copy the code

7 Format plug-ins with code

I develop most of my projects in VSCode, so if you use VSCode, make sure Prettier is installed to keep code pretty.

This plugin will save you the time you spend formatting code. Thanks to it, you can use this time to focus more on code quality.

❤️ Love triple punch

Through reading, if you think you have something to gain, you can love the triple punch!!

I am Wu Liu, like innovation, tamping source Code, focus on Vue3 source Code, Vite source Code, front-end engineering and other technical fields to share, welcome to pay attention to my “wechat public number: Code Center”.