Writing clean code is the key to creating applications that are maintainable and scalable. In this lesson, we are going to cover some of the rules you should follow in order to write clean code using JavaScript.
Write readable code
First of all, you should make sure the variables, functions and classes are properly names. The name should describe the purpose of the code, and also readable. For instance, the following examples are not appropriate:
1// This example is too short
2function a(b, c) {
3 return b + c;
4}
5
6// This example is too complicated
7function addNumberOneAndNumberTwo(numberOne, numberTwo) {
8 return numberOne + numberTwo;
9}
If the name is too short, it does not describe exactly what this function does. If the name is too complicated, they lose readability. Instead, you must ensure the name is descriptive but also concise like this:
1function add(num1, num2) {
2 return num1 + num2;
3}
This is a good name because add
accurately describes the purpose of this function, but not too complicated like the previous example.
Write descriptive comment
You must also make sure that your code is properly commented. Whenever you create a function, a class, or whenever you create a new feature, on top of the descriptive names, there should also be a comment explaining exactly what the code does.
Similarly, the comment should also be descriptive and concise. The following example is too long and difficult to read.