This is the 11th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Writing clean code is something every developer needs to do, and in this article we’ll cover clean coding principles for naming, using variables, functions, and so on, as well as some clean coding best practices specific to JavaScript.

What does clean coding mean?

Clean coding means that you first write code for yourself and your colleagues, not for machines, and that your code must be easy for humans to understand.

JS clean coding best practices

About the variable

  • Can useA man is known by his nameAvoid single-letter names. If you follow this, your name will come in handy for searches.

For example, if you name your variable, d, I, etc.,….. when you want to search 😑

About the function

useObject.assignSet object defaults

//Good
function setStyle(config){
    config = Object.assign(
        {
          color:"black",bg:"#333333"
        },
        config
    );
   //do something
}
Copy the code

Avoid long parameter lists

Use single object parameter or destruct assignment instead. It also makes it easier to work with optional parameters.

// DON'T
function getRegisteredUsers (fields, include, fromDate, toDate) { /* implementation */ }
getRegisteredUsers(['firstName', 'lastName', 'email'], ['invitedUsers'], '2016-09-26', '2016-12-13')

// DO
function getRegisteredUsers ({ fields, include, fromDate, toDate }) { /* implementation */ }
getRegisteredUsers({
  fields: ['firstName', 'lastName', 'email'],
  include: ['invitedUsers'],
  fromDate: '2016-09-26',
  toDate: '2016-12-13'
})
Copy the code

Query or modify

A function should do something (modify) or answer something (query), but not both.

Keep the function as simple as possible

A function should only do one thing. Do not perform multiple operations in a function.

Not recommended

Recommended way to write

modular

You can declare multiple functions in a file and then export them for use

The sample

//js file function add(a, b) {return a + b} function subtract(a, b) {return a-b} module.exports = {add, Const {add, subtract} = require('./calculations') console.log(5, add(3, 2))Copy the code

Function names should be descriptive

The function name should be a verb or phrasal verb, which needs to convey its intent, as well as the order and intent of the arguments.

Do not contaminate global variables

If you need to extend an existing object, it is recommended to use ES6’s classes and inheritance instead of creating functions on the prototype chain of native objects

About Naming conventions

  • letIt is recommended to use [name of hump].
  • constIt is recommended to use the uppercase snake name at the top of the document, not the top, but the hump name.
  • classPASCAL’s nomenclature is recommended.
  • functionFunction recommended to use [hump naming]
  • BooleanAdd one in front of the recommended nameis, such asconst isTeacher = true // OR false

Hump method

Camel nomenclature is when the name of a variable or function is a unique identifier composed of one or more words joined together.

The first word begins with a lowercase letter; Capitalize the first letter of the second word or start each word with a capital letter,

For example, firstName, lastName

Serpentine nomenclature

Serpentine nomenclature consists of all lowercase letters and underscores connected by a sliding line between two words,

For example, first_name, last_name

The upper case should look like this

FIRST_NAME   LAST_NAME
Copy the code

PASCAL nomenclature

It’s similar to camel nomenclature except that camel nomenclature is lowercase, whereas PASCAL nomenclature is uppercase; 【 PASCAL naming rules: Big hump naming rules 】

For example: MyClass

Recommended usage for determining whether an attribute exists

Writing is not recommended

Recommend writing

// Good
const object = {
  name: 'Axjy'
};
if ('name' in object) {
  // ...
}
Copy the code

Some recommended uses for judgment

You are advised to use array. includes

Determines whether the parameter exists in the array

Every is recommended

Here is an example

  • Trying to judge that everyone is in a good mood

Writing is not recommended

Recommend writing

//Good
function demo2() {
  const isAllGood = peoples.every(item => item.mood == 'good');
  console.log(isAllGood);
}
Copy the code

Use array. some

Here is an example

  • Trying to determine if there is a bad mood

Recommend writing

//Good
function demo() {
  const isAnyBad = peoples.some(item => item.mood == 'bad');
  console.log(isAnyBad);
}
Copy the code

Using a prettier

Working in a team requires a clear style guide and format. ESLint provides a huge set of rules that you can customize to suit your needs. There’s also ESLint –fix, which corrects some errors, but not all of them.

Instead, you are advised to use Prettier to format the code. This way, developers don’t have to worry about code formatting and just write high-quality code.

conclusion

The above is just to provide some inspiration and reflection, not by any standard, nor is it necessarily necessary.

reference

JavaScript Clean Coding Best Practices

12 tips for writing clean and scalable JavaScript


Leave a like if you get something! 😘